Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load UIWebView in a background fetch

Short version: in my app background fetch works like a charm except that when I try to load contents in a webview it does nothing at all!

Long version: I set the right capabilities in the project, set the fetch interval and implement the

- (void) application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

method as in the examples and it works. But then, to complete my background fetch I need to load some contents in a UIWebView. And this doesn't work. Simply the process somehow "get lost" when i call:

[myWebview loadRequest:request];

(of course it works when in foreground, but does nothing when in background).

I also try to force the webview to be loaded in the main thread, but then the system simply halt it 'till the app return in foreground mode (it make sense, we are in background!)

So, there's a way to load a UIWebView while in background? Please note I can't simply download the contents with NSURLSession, 'cause the webpage contains javascript that load some of the frames (and I can't ask for a redesign of the webpage).

Edit: probably I wasn't crear enough when I wrote the question, but trying to execute a task it in the main_queue (with a dispatch_async o likewise methods) while in a background fetch does not work. I tried it before asking...

like image 756
il Malvagio Dottor Prosciutto Avatar asked Oct 30 '13 16:10

il Malvagio Dottor Prosciutto


2 Answers

When you want to update elements from the user interface, you have to access them in the main queue (or thread) of the application. What I would recommend is for you to keep getting the data you need in the background, but when it is time to update your UIWebView, do it in the main thread. You can do it like this:

    dispatch_async(dispatch_get_main_queue(), ^{

        // Load fetched data in the Web View

    });   

or you could create a method that updates the data on the UIWebView and call it from the background thread using:

[self performSelectorOnMainThread:@selector(method:) withObject:fetchedData waitUntilDone:YES];

This will ensure that you access the UIWebView from the correct thread.

Hope this helps.

like image 103
Eduardo Arenas Prada Avatar answered Sep 29 '22 05:09

Eduardo Arenas Prada


At 11/11/2013 (iOS 7.0.3) looks like is not possible. I just leave this answer so people will not get wrong info.

The solution of Eduardo Arenas Prada works perfectly if your application is in foreground, but not in a background fetch sadly.

like image 25
il Malvagio Dottor Prosciutto Avatar answered Sep 29 '22 05:09

il Malvagio Dottor Prosciutto