17

I am trying out afnetworking 2.0 and just trying to figure out how to cancel specific tasks. The old way would be to use something like

[self cancelAllHTTPOperationsWithMethod:@"POST" path:@"user/receipts"]

but I dont see anything like this in 2.0

I created a sub class of AFHTTPSessionManager which gives me access to the array of pending tasks and I can cancel them directly but I dont know how to identify 1 task from another so I can cancel only specific tasks. Task does have an taskidentifier but this doesnt appear to be what I need.

NSString *path = [NSString stringWithFormat:@"user/receipts"];
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:[prefs valueForKey:@"uuid"] password:self.store.authToken];
[self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            errorBlock(error);
        }];

now if i wanted to cancel this request only how would I approach this?

3 Answers 3

34

You can store the task in a variable so you can access it later:

NSURLSessionDataTask* task = [self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            errorBlock(error);
        }];

Then simply cancel it with [task cancel].

Another way would be to save the task ID of the task and later ask the URL session for its tasks and identify the task you wish to cancel:

// save task ID
_savedTaskID = task.taskIdentifier;

// cancel specific task
for (NSURLSessionDataTask* task in [self dataTasks]) {
    if (task.taskIdentifier == _savedTaskID) {
        [task cancel];
    }
}
2
  • 1
    @phix23 any idea why [task cancel] is still calling the success callback when being canceled? Mar 17, 2014 at 0:13
  • I didn't thought about declaring the GET method in a NSURLSessionDataTask. Thank you very much !
    – Jerome
    Mar 24, 2014 at 10:46
7

No need to save it, here is my implementation, use your subclass of AFURLSessionManager for cancelling specific request:

- (void)cancelAllHTTPOperationsWithPath:(NSString *)path
{
    AFURLSessionManager * yourSessionManager = [self getSessionManager];

    [[yourSessionManager session] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        [self cancelTasksInArray:dataTasks withPath:path];
        [self cancelTasksInArray:uploadTasks withPath:path];
        [self cancelTasksInArray:downloadTasks withPath:path];
    }];
}

- (void)cancelTasksInArray:(NSArray *)tasksArray withPath:(NSString *)path
{
    for (NSURLSessionTask *task in tasksArray) {
        NSRange range = [[[[task currentRequest]URL] absoluteString] rangeOfString:path];
        if (range.location != NSNotFound) {
            [task cancel];
        }
    }
}
2
  • 2
    Up-voted, but what about paths that are a substring of another request path? i.e. "/item/1" and "/item/11" Canceling item 1 would also cancel 11. Wouldn't ...URL] path] isEqualToString:path] be a better comparison? Jan 24, 2014 at 16:07
  • thank you for pointing that out... I used this approach so that if a user wants to cancel all the tasks with same context it can be done easily i.e. "/school/class/students" would cancel all requests for "/school/class/students/id001" to ..id100 thus have also not put a break in the loop. Your problem can be handled by using "/item/01" and "/item/11". Anyway the comparison can be changed as per the requirement.
    – Zaraki
    Jan 28, 2014 at 7:01
0

you can do the following

NSArray *operations = [[[MyClient sharedClient] operationQueue] operations];
if(operations && operations.count > 0){
    for (NSOperation *operation in operations) {
        if([operation isKindOfClass:[AFHTTPRequestOperation class]]){
            AFHTTPRequestOperation *httpOperation = (AFHTTPRequestOperation *)operation;
            NSLog(@"%@", [[httpOperation request] URL]);
            //--- if this is your request then cancel it --> [httpOperation cancel];
        }
    }
}

Where MyClient is a child of AFHTTPClient and the function sharedClient is a static function which returns a singleton instance of MyClient

2
  • Thank you for downgrading, but please specify the reason to share the knowledge.
    – Saeed
    Aug 6, 2014 at 3:22
  • 2
    Probably because your solution uses AFHTTPClient, which is AFN 1.x only. The question was for AFN 2.0.
    – koen
    Oct 3, 2014 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.