1

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

4

1 回答 1

6

您可以使用库 AFNetworking/AFNetworkActivityLogger

https://github.com/AFNetworking/AFNetworkActivityLogger

来自文档:

AFNetworkActivityLogger 是 AFNetworking 2.0 的扩展,可在发送和接收网络请求时记录它们。

用法:

[[AFNetworkActivityLogger sharedLogger] startLogging];

输出:

GET http://example.com/foo/bar.json
200 http://example.com/foo/bar.json

使用开发日志级别,您也应该有 responseHeaderFields 和 responseString

于 2014-04-29T17:24:19.390 回答