TaskIdentifier in NSURLSession not Changing

1.3k views Asked by At

I am trying to upload multiple videos through NSURLSession in my App. But taskIdentifier for every request is coming same. Its not getting change for every request. How can we keep track for our request? How can we know which one gets complete?

This is my Code:

   _uploadTask = [_session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    id jsonResponse= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

   }];

 [_uploadTask resume];
 NSLog(@" task ID %ld",_uploadTask.taskIdentifier);

Here: _uploadTask is instance of NSURLSessionUploadTask, _session is an instance of NSURLSession, request is NSMutableURLRequest instance and body is NSData. OutPut is:

"task ID 1"
3

There are 3 answers

1
Murtaza Khursheed Hussain On

I would do the following to keep track

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://someurl.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *someTask= [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"error!");
        } else {
            NSLog(@"task successful!");
        }
    }];
    [someTask resume];
0
AR89 On

Had the same problem

If you're creating the URLSession each time that you make the request the ID will always starts with 1 You must create the URLSession just once

0
GeneCode On

First, add a property so you can store the identifier created by NSURLSession. This id is created automatically so there is no knowing whether it is 1,2,3 or whatever. So u need to store it during task creation.

_uploadTask = [_session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    // do your thing

   }];
 _myTaskID = [_uploadTask taskIdentifier];
 [_uploadTask resume];

Then call this method to cancel that task

- (void)cancelTaskByIdentifer:(long)myTaskID {

    [[NSURLSession sharedSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {

        if (!dataTasks || !dataTasks.count) {
            return;
        }
        for (NSURLSessionTask *task in dataTasks) {
            long taskId = [task taskIdentifier];
            if (taskId==myTaskID) [task cancel];
        }
    }];
}

For example:

[self cancelTaskByIdentifier:_myTaskID];