我正在将我的项目迁移到 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
它是 nil。从而在控制台中打印空值。但是,该方法仍会返回适当的任务对象。这里发生了什么事?如何正确记录每个呼叫的请求/响应?