Cos*_*min 56 debugging ios afnetworking-2 alamofire
有没有办法使用Alamofire记录每个请求/响应(类似于AFNetworkActivityLogger)?
我知道Printable,DebugPrintable和Output(cURL),但它们并不是我想要的.
clo*_*ach 46
这样的事情可能就是你想要的:
extension Request {
public func debugLog() -> Self {
#if DEBUG
debugPrint(self)
#endif
return self
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.debugLog()
.response {…}
Run Code Online (Sandbox Code Playgroud)
如果要打印所有响应,可以编写自己的响应方法,类似于本教程顶部的responseObject()方法:
http://www.raywenderlich.com/87595/intermediate-alamofire-tutorial
[更新:根据@trauzti的请求在下面添加.]
以下是为了在每个请求上打印输出,可以采用responseObject()方法.
警告:我没有亲自测试过此代码,可能会在生产中做出不同的选择.这简单地说明了Wenderlich教程代码如何包含调试日志记录.另请注意:由于本教程是Swift 2.0之前的版本,因此我使用了旧的println()而不是print().
@objc public protocol ResponseObjectSerializable {
init(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Alamofire.Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
let serializer: Serializer = { (request, response, data) in
#if DEBUG
println("Request: \(request.URL)")
#endif
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
if response != nil && JSON != nil {
#if DEBUG
println("Response:")
debugPrint(JSON)
#endif
return (T(response: response!, representation: JSON!), nil)
} else {
#if DEBUG
println("Failed Serialization:")
debugPrint(serializationError)
#endif
return (nil, serializationError)
}
}
return response(serializer: serializer, completionHandler: { (request, response, object, error) in
completionHandler(request, response, object as? T, error)
})
}
}
Run Code Online (Sandbox Code Playgroud)
ull*_*trm 35
这是一个甜蜜的小豆荚:https://github.com/konkab/AlamofireNetworkActivityLogger
将其添加到您的podfile:
pod 'AlamofireNetworkActivityLogger', '~> 2.0'
Run Code Online (Sandbox Code Playgroud)
在你的AppDelegate中:
import AlamofireNetworkActivityLogger
Run Code Online (Sandbox Code Playgroud)
然后在你的didFinishLaunchingWithOptions,添加这个:
NetworkActivityLogger.shared.level = .debug
NetworkActivityLogger.shared.startLogging()
Run Code Online (Sandbox Code Playgroud)
编辑:我实际上遇到了在生产中崩溃的问题.为了安全起见,使用"build flags"仅在调试中使用它,如下所示:
#if DEBUG
NetworkActivityLogger.shared.level = .debug
NetworkActivityLogger.shared.startLogging()
#endif
Run Code Online (Sandbox Code Playgroud)
0xc*_*ced 15
从 Alamofire 5 开始,最简单的方法是定义一个EventMonitor子类:
final class AlamofireLogger: EventMonitor {
func requestDidResume(_ request: Request) {
let body = request.request.flatMap { $0.httpBody.map { String(decoding: $0, as: UTF8.self) } } ?? "None"
let message = """
?? Request Started: \(request)
?? Body Data: \(body)
"""
NSLog(message)
}
func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value>) {
NSLog("?? Response Received: \(response.debugDescription)")
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的会话中使用它:
let session = Session(eventMonitors: [ AlamofireLogger() ])
Run Code Online (Sandbox Code Playgroud)
此示例代码改编自https://github.com/Alamofire/Alamofire/issues/2867#issuecomment-509662892
ali*_*ali 10
Timberjack正是你所期待的.Timberjack是一个简单,不引人注目的网络活动记录器.记录您的应用程序发出的每个请求,或者如果您愿意,只限制使用某个NSURLSession的请求.它也适用于Alamofire,如果这是你的事情.
https://cocoapods.org/pods/Timberjack
用法:
import Alamofire
import Timberjack
class HTTPManager: Alamofire.Manager {
static let sharedManager: HTTPManager = {
let configuration = Timberjack.defaultSessionConfiguration()
let manager = HTTPManager(configuration: configuration)
return manager
}()
}
Run Code Online (Sandbox Code Playgroud)
在 Alamofire 5 中 URLRequest 是异步创建的,这意味着
extension Request {
public func debugLog() -> Self {
#if DEBUG
debugPrint(self)
#endif
return self
}
}
Run Code Online (Sandbox Code Playgroud)
不再是最好的解决方案。相反,建议cURLDescription如下调用:
let request = AF.request(<Your request>))
request.cURLDescription { (curl) in
print("CURL \(curl)")
}
request.responseJSON { response in
//Do something with your response...
}
Run Code Online (Sandbox Code Playgroud)
或者
extension Request {
public func debugLog() -> Self {
#if DEBUG
cURLDescription(calling: { (curl) in
debugPrint("=======================================")
print(curl)
debugPrint("=======================================")
})
#endif
return self
}
}
Run Code Online (Sandbox Code Playgroud)
为Alamofire 4.0+ Swift 3添加以上答案
extension DataRequest {
public func LogRequest() -> Self {
//Your logic for logging
return self
}
}
Run Code Online (Sandbox Code Playgroud)
要求时
Alamofire.request(requestUrl, method: .post, parameters: parameter, encoding: JSONEncoding.default)
.LogRequest()
.responseJSON { response in
//Do your thing
}
Run Code Online (Sandbox Code Playgroud)
如果您想在任何情况下取消请求(这是我想要的),则self.cancel()可以在返回自己之前的任何位置
| 归档时间: |
|
| 查看次数: |
27271 次 |
| 最近记录: |