Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 2.0 cancel specific task

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?

like image 730
glogic Avatar asked Sep 25 '13 09:09

glogic


2 Answers

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];
    }
}
like image 138
Felix Avatar answered Nov 09 '22 12:11

Felix


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];
        }
    }
}
like image 24
Zaraki Avatar answered Nov 09 '22 12:11

Zaraki