如何使用AFHTTPSessionManager记录每个请求/响应?

hgw*_*tle 1 ios afnetworking afnetworking-2 nsurlsessiontask

我正在将我的项目迁移到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);
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)

dataTaskWithRequest:completionHandler方法成功拦截每个调用,因此我认为这是覆盖的正确方法,但是当我尝试在completionHandler中记录任务时,task是nil.因此在控制台中打印空值.但是,仍然从该方法返回适当的任务对象.这里发生了什么事?如何正确记录每个呼叫的请求/响应?

pri*_*x79 6

您可以使用库AFNetworking/AFNetworkActivityLogger

https://github.com/AFNetworking/AFNetworkActivityLogger

来自文档:

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

用法:

[[AFNetworkActivityLogger sharedLogger] startLogging];
Run Code Online (Sandbox Code Playgroud)

输出:

GET http://example.com/foo/bar.json
200 http://example.com/foo/bar.json
Run Code Online (Sandbox Code Playgroud)

使用devel日志记录级别,你也应该有responseHeaderFields和responseString