Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async call a method using IOS 4

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?

like image 692
Tony Avatar asked Nov 29 '22 03:11

Tony


2 Answers

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

like image 137
cobbal Avatar answered Dec 05 '22 01:12

cobbal


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];
}
like image 43
Krizz Avatar answered Dec 05 '22 00:12

Krizz