I want to call a method asynchronically. It's a method that gets HTML from a server and sets it to a UIWebView
:
NSString *htmlTest = [BackendProxy getContent];
[webView loadHTMLString:htmlTest baseURL: nil];
[webView setUserInteractionEnabled:YES];
I want to start an activity indicator in the UIWebView
during the data fetch, so I need to call getContent
asynchronically. How can I achieve that?
This is a great use case for GCD, Apple's new(ish) concurrency API.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^ {
// Background work here
NSLog(@"Finished work in background");
dispatch_async(dispatch_get_main_queue(), ^ {
NSLog(@"Back on main thread");
});
});
Here's the documentation on dispatch queues
I suggest performSelectorInBackground:withObject:
of NSObject
.
Like the following:
- (void)loadIntoWebView: (id) dummy
{
NSString *html = [BackendProxy getContent];
[self performSelectorOnMainThread: @selector(loadingFinished:) withObject: html];
}
- (void)loadingFinished: (NSString*) html
{
// stop activity indicator
[webView loadHTMLString:html baseURL: nil];
[webView setUserInteractionEnabled:YES];
}
- (void) foo
{
// ...
// start activity indicator
[self performSelectorInBackground: @selector(loadIntoWebView:) withObject: nil];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With