I'm using AFNetworking and I am overridding -dataTaskWithRequest:completionHandler:
to basically MITM my request and do some error handling prior to calling the actual response block. However, I need access to the NSURLSessionDataTask object that the -dataTaskWithRequest:completionHandler:
method creates, inside my intercepted completion handler. So my override of the method looks like this:
-(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];
}
Is this possible?
I know that AFNetworking could add this quite easily as the response parameter of the completion handler is set as task.response
in AFURLSessionManager
, which is the class that contains the -URLSession:task:didCompleteWithError:
that calls the completion handler.
I've figured it out. By declaring the block inline and assigning the super call to a variable, I'm able to use the resulting task object:
-(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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.