GCD: two parallel animations on UIViews

You ask:

Can someone please add your thoughts and let me how can I have two separate threads running concurrently and updating the UI elements?

You can simple have those thread do their requests and parsing in the background threads, and then have them dispatch the model and UI updates back to the main queue.

For example, you could do something like:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // issue first web service request

   // when done, update the UI

   dispatch_async(dispatch_get_main_queue(), ^{
       // update the model here

       // also issue the `reloadData` (or whatever table updates you want) 
       // for the first table view
   });
});

and

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // issue second web service request

   // when done, update the UI

   dispatch_async(dispatch_get_main_queue(), ^{
       // update the model here

       // also issue the `reloadData` (or whatever table updates you want) 
       // for the second table view
   });
});

These two will run concurrently (because all global queues are concurrent queues), but UI/model updates will be dispatched to the main queue, which will ensure everything stays synchronized, that UI updates happen successfully, etc. Thus you enjoy the concurrency offered by background queues, but you’ll take advantage of the serial main queue where you need to.

Clearly, the above assumes that you’re dispatching the network requests to some background queue (and we’ll use the default global queue), but the precise mechanism for issuing asynchronous network requests can vary greatly (and might not involve any dispatching at all). If you need specific counsel, you should share precisely how you’re issuing the requests to your web services (e.g. AFNetworking? NSURLConnection (and if NSURLConnection, one of the convenience methods or delegate based approach)? NSURLSession?), as the implementation details will vary based upon how you’re making the request.

But the idea is simple: Perform the network service requests asynchronously, and then make sure that upon the completion of the request, you perform the resulting model and UI updates on the main queue. This way, you enjoy the concurrency of the requests, but the UI updates happen on the main queue.

Leave a Comment