7

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...

4

2 回答 2

3

当您想从用户界面更新元素时​​,您必须在应用程序的主队列(或线程)中访问它们。我建议您在后台继续获取您需要的数据,但是当需要更新您的 时UIWebView,请在主线程中进行。你可以这样做:

    dispatch_async(dispatch_get_main_queue(), ^{

        // Load fetched data in the Web View

    });   

或者您可以创建一个更新数据的方法,UIWebView并使用以下方法从后台线程调用它:

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

这将确保您从正确的线程访问 UIWebView。

希望这可以帮助。

于 2013-10-30T17:00:33.327 回答
2

在 2013 年 11 月 11 日(iOS 7.0.3)看起来是不可能的。我只是留下这个答案,这样人们就不会得到错误的信息。

如果您的应用程序在前台,但Eduardo Arenas Prada 的解决方案非常适用,但遗憾的是不能在后台获取。

于 2013-11-12T10:05:53.607 回答