Question

I used to do what I wanted with NSURLConnection.

  • I would create a new custom NSOperation object
  • setup my NSMutalbeRequest and when ready trigger the operation witch would queue the operation...
  • in there I would have the NSURLConnection delegate methods and with that I could track all progress, completion, errors etc...

So, the point is, request would be contained in its own operation and the delegate calls would happen in there, having a 1-to-1 relationship between the request operation object and the NSURLConnection delegate.

I am not sure HOW to do this with a NSURLSession. With the NSURLSession I can trigger all the dataTasks I want for all the GET calls I want to perform. However I setup the shared session using this call:

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;

So the problem I am trying to solve is how can I track multiple GET requests progress if I have only one object where all the delegate calls happen? I only have ONE DELEGATE in there. So now I have 1 session, 1 delegate object but I have multiple GET requests happening at the same time.

I know each task has a "taskIdentifier", but that requires me to have some kind of dictionary.

For example when the delegate call:

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data

is called, then I'd have to look up the task in a dictionary and then the object I'd get from the dictionary could have the reference to what I need to track the progress of that one request...

I am not sure what the best way to solve this problem is? Does anybody know how this should be done?

Was it helpful?

Solution 3

So,

what worked best for me so far is using the NSDictionary approach. That allows the NSURLSession delegates to get a hold of the right data task and handle multiple requests at once.

I am not sure if this is the best approach, but my app is now running lots of requests and things seems to work fine.

OTHER TIPS

Basically what you need to do is set accessibility label for each requests

    for task 1

    [dataTask setAccessibilityLabel:@"label1"];

    for task 2

    [dataTask setAccessibilityLabel:@"label2"];

and then in delegate methods check for accessibility label

    if([dataTask.accessibilityLabel  isEqual: @"label1"])
     {
        // handle data from first task

     }

     if([dataTask.accessibilityLabel  isEqual: @"label2"])
     {
       // handle data from second task

     }

You could also instantiate the NSURLSessionDataTask with your own subclass of NSURLRequest which you can retrieve from task.originalRequest in the session delegate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top