Search code examples
iosafnetworkinggrand-central-dispatchnsurlsessionnsoperationqueue

Different DispatchQueue for different requests


I want to have different priorities for different http requests and I want to be able to stop/pause some requests immediately and to execute only some of them if I have a request with High priority. I was going to use different approaches, but it seems that all of them are deprecated now:

1) To use AFHTTPRequestOperation, so I can create different OperationQueue base on DispatchQueue and add operations there, but it's deprecated in a new version of AFNetworking

2) To use different DispatchQueues with different priorities for different Synchronous requests (using NSURLConnection.sendSynchronousRequest) (so I can stop some queues if I have highest priority operations and I can cancel operations immediately). But as far as I understand according to Stackoverflow Question , this way is deprecated, so I can't send a Synchronous request.

I understand that there are ways where Requests seem to be Synchronous using semaphores, but that's only an illusion, because all the requests will be executed in the queues I can't control.

Are there any ways to control the DispatchQueue (or OperationQueue) where the request is executed?


Solution

  • You should/could use NSURLSessionTask/URLSessionTask subclasses to grab data from the network. You could easily encapsulate them inside one NSOperation/Operation subclasses (see this slide.

    You would just need to add cancellation support to it. You can find information about cancellation inside the Responding to the Cancel Command section of the NSOperation documentation.

    To play with priorities you have several tools:

    • To handle priorities between OperationQueue instances, you can attribute them different qualityOfService values.
    • To handle priorities between Operation instances, you can attribute them different qualityOfService, queuePriority or threadPriority values.

    Some additional explanation about those parameters can be found in the Prioritize Work with Quality of Service Classes section of the Energy Efficiency Guide for iOS Apps.