I have my app making a google API call using dispatch_async and getting the JSON results that I am parsing through. I want to implement a progress view such that it updates depending on how many results from JSON response that I have parsed through.
So my dispatch_async Google API call is:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
});
My fetchResultsForGoogle: withObject:
method parses through the results, and I want to display the progress view on the screen with the number of processed results. So within the fetchResultsForGoogle...
method, I want to have:
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @" complete"];
self.progressViewLabel.text = percentText;
But I think understand that when the dispatch_async is performing on another thread, you can't update view on the main thread without using dispatch_async(dispatch_get_main_queue()
. In an attempt to solve this, I tried two ways of implementing this (shown below) but either of these ways don't work for me (progressView
and progressViewLabel
don't update at all).
Plan A:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
dispatch_async(dispatch_get_main_queue(), ^{
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @"complete"];
NSLog(@"Percentage: %@", percentText);
self.progressViewLabel.text = percentText;
});
});
Plan B:
dispatch_async(myQueue, ^{
NSData* data1 = [NSData dataWithContentsOfURL:googleURL];
[self performSelectorOnMainThread:@selector(fetchResultsForGoogle:) withObject:data1 waitUntilDone:YES];
});
And within fetchResultsForGoogle...
method:
dispatch_async(dispatch_get_main_queue(), ^{
float percentage = (float)counter/(float)totalItems;
self.progressView.progress = percentage;
NSString *percentText = [NSString stringWithFormat:@"%f %% %@", percentage, @"complete"];
NSLog(@"Percentage: %@", percentText);
self.progressViewLabel.text = percentText;
});
So any ideas or tips regarding the correct way to implement this is very much appreciated!
EDIT-SOLVED IT
I fixed it. In dispatch_async
block, I was passing it to performSelectorOnMainThread
. Therefore when I was trying to update the progress view in performSelectorOnMainThread
, the UI won't update until the dispatch_async
was completed.
So, I changed it to performSelectorInBackgroundThread
inside the dispatch_async
block and now the performSelectorOnMainThread
updates the UI like the way it should.
I am new to all this, but I am glad I am still learning new things.