Reputation: 20076
I like to show a loading message when the app is fetching news and videos. Currently, I have the following code:
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[self loadVersion];
[self loadFeaturedNews];
[self loadFeaturedVideo];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self dismissViewControllerAnimated:NO completion:nil];
});
});
I would like to dismiss the controller and hide the progress view only when all the tasks (news, videos) are loaded.
Upvotes: 0
Views: 1165
Reputation: 437622
If you're using AFNetworking, you might want to look at enqueueBatchOfHTTPRequestOperations
. I'd refer you to the AFNetworking FAQ:
How can I wait for a group of requests to finish before processing them?
Use [
enqueueBatchOfHTTPRequestOperationsWithRequests
] or [enqueueBatchOfHTTPRequestOperations
] to batch a series of requests together, specifying a callback for when all of the requests have finished. As mentioned in the question about waiting for completion blocks to finish, you may not want to set completion blocks on each individual operation, and instead access the response object properties directly in the batch completion block.
I gather that loadVersion
, loadFeaturedNews
, and loadFeaturedVideo
methods are each asynchronously downloading content. If you were using NSURLConnection
, I would suggest changing them to operate synchronously. The specifics of the solution will vary depending upon how you're currently downloading stuff in those routines e.g. if you're using NSURLConnection
method, initWithRequest
, you could use sendSynchronousRequest
.
Personally, I'd be inclined to combine that with doing the requests concurrently with dispatch groups or NSOperationQueue
dependencies, but first focus on getting them to run synchronously. I'd actually use NSOperationQueue
so I could easily cap the number of concurrent operations to four, or something reasonable like that.
By the way, I'm not suggesting you change the code in your question at all. Keep that dispatch_async
. I'm suggesting you fix the loadVersion
, loadFeaturedNews
, and loadFeaturedVideo
methods, themselves, to operate synchronously.
Upvotes: 1
Reputation: 17655
Then use completion handler for this. in that you can write your code which is to be executed after completion
completion:^ (BOOL finished) {
}
Upvotes: 0