在Intercepted Completion Handler中获取NSURLSessionDataTask

时间:2015-01-06 14:18:06

标签: ios afnetworking

我正在使用AFNetworking并且我覆盖-dataTaskWithRequest:completionHandler:基本上MITM我的请求并在调用实际响应块之前进行一些错误处理。但是,我需要访问-dataTaskWithRequest:completionHandler:方法在我截获的完成处理程序中创建的NSURLSessionDataTask对象。所以我对方法的覆盖如下所示:

-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {

    void (^interceptedCompletionHandler)(NSURLResponse *, id, NSError *) = ^void(NSURLResponse * response, id responseObject, NSError * error) {
        if (error) {
            // Do custom stuff here that needs to use task.taskIdentifier
        }

        // Then call the original completion handler
        completionHandler(response, responseObject, error);

    }

    return [super dataTaskWithRequest:request completionHandler:interceptedCompletionHandler];
}

这可能吗?

我知道AFNetworking可以很容易地添加这个,因为完成处理程序的响应参数在task.response中设置为AFURLSessionManager,这是包含调用-URLSession:task:didCompleteWithError:的{​​{1}}的类完成处理程序。

1 个答案:

答案 0 :(得分:1)

我已经弄清楚了。通过声明块内联并为变量分配超级调用,我可以使用生成的任务对象:

-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {

    __block NSURLSessionDataTask* task = [super dataTaskWithRequest:request completionHandler:
                                      ^void(NSURLResponse * response, id responseObject, NSError * error)
    {
        // I can use task here
        if (error) {
            // Do custom stuff here that needs to use task.taskIdentifier
        }

        // Then call the original completion handler
        completionHandler(response, responseObject, error);

    }

    return task;
}