我将我的项目迁移到AFNetworking 2.0。使用AFNetworking 1.0时,我编写了代码来记录控制台中的每个请求/响应。这是代码:
-(AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *, id))success
failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
AFHTTPRequestOperation *operation =
[super HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject){
[self logOperation:operation];
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
failure(operation, error);
}];
return operation;
}
-(void)logOperation:(AFHTTPRequestOperation *)operation {
NSLog(@"Request URL-> %@\n\nRequest Body-> %@\n\nResponse [%d]\n%@\n%@\n\n\n",
operation.request.URL.absoluteString,
[[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding],
operation.response.statusCode, operation.response.allHeaderFields, operation.responseString);
}
我尝试使用AFNetworking 2.0做同样的事情,根据我的理解,这意味着使用NSURLSessionDataTask
对象而不是AFHTTPRequestOperation
。这是我拍摄的。
-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {
NSURLSessionDataTask *task = [super dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error){
[self logTask:task];
completionHandler(response, responseObject, error);
}];
return task;
}
-(void)logTask:(NSURLSessionDataTask *)task {
NSString *requestString = task.originalRequest.URL.absoluteString;
NSString *responseString = task.response.URL.absoluteString;
NSLog(@"\n\nRequest - %@\n\nResponse - %@\n\n", requestString, responseString);
}
dataTaskWithRequest:completionHandler
方法成功拦截每个调用,因此我认为这是正确的覆盖方法,但是当我尝试在completionHandler中记录任务时,task
为零。因此在控制台中打印空值。但是,仍然从该方法返回适当的任务对象。这里发生了什么?如何正确记录每次通话的请求/响应?
答案 0 :(得分:5)
您可以使用库AFNetworking / AFNetworkActivityLogger
https://github.com/AFNetworking/AFNetworkActivityLogger
来自doc:
AFNetworkActivityLogger是AFNetworking 2.0的扩展记录 发送和接收网络请求。
用法:
[[AFNetworkActivityLogger sharedLogger] startLogging];
输出:
GET http://example.com/foo/bar.json
200 http://example.com/foo/bar.json
使用devel日志记录级别,你应该有responseHeaderFields和responseString