user1107173 user1107173 - 2 months ago 11
iOS Question

NSOperationsQueue: Managing identical requests

I need to hit the same

endpoint
in the following situations:


  1. When a view reappears on the screen
    viewWillAppear
    .

  2. Every 5 seconds during the life-cycle of a view controller (while the view is being presented).

  3. After the app returns from
    background
    to
    foreground
    .



This creates at least 2, if not 3,
concurrent
requests to the same
endpoint
when my app returns to
foreground
, especially during a slow internet connection.

I know I can limit the number of
concurrent
requests in the
Queue
to 1, but sometimes I do have a need to hit a few different
endpoints
concurrently
so I am hoping to find an alternative.

I am using
NSURLSession
with
NSOperationsQueue
to make these calls. Is there a best practice to handle this with
NSOperationsQueue
?

Answer

It's possible to coalesce (combine) NSOperation subclasses that are the same task together so removing any redundant network calls. In order to do this each operation needs to have an identifier that is unique to the task (not the operation itself) and can be used to determine if that operation is in the queue. Once an operation has been determined as being in the queue, we can then take the new operation's block/closure callback and insert it into the older operations structure so ensuring that when the older operation's task is complete, both callbacks are triggered. This helps to avoid a scenario where you have missing callbacks in your app.

I've written an article that covers this exact topic:

http://williamboles.me/removing-bolierplate-when-coalescing-nsoperations/

Please note, that this only works for operations that are still in the queue, if you want to limit operations based on a time interval then you need to extend your "traffic controller", like "Code Different" commented.