View Full Version : Background loading UIWebView
Feb 23, 2011, 08:32 AM
I have a webview that is only displayed once content has been loaded. So basically I have a background thread that does a loadRequest with URL and then in webViewDidFinishLoad I show the webview on screen. Seems to work, but the problem is it doesn't work all the time, like 3 out of 5 times then it will just stop working ie webViewDidFinishLoad is not called at all. I'm not sure if it's just timing out although the target source URL seems to be working each time I refresh it in my browser. Any ideas what could cause this?
Also, is this even the best way to do this, would it be better using ASIHttpRequest to handle this sort of stuff?
Feb 23, 2011, 08:51 AM
It's not legal to access UIWebView from a background thread. Predicted results are what you're seeing. Sometimes it works, and sometimes it doesn't.
I've also found UIWebView to be slow to load, at least the first time. I never came up with a real workaround. You might try to put it offscreen until it's loaded or make it hidden until its loaded. It might be that loading it with a simple string or local file might speed up its loading after that.
If you want to load the remote content and store it locally and then load from that it might also be faster.
Feb 23, 2011, 09:03 AM
Thanks. When you say illegal to access from background thread, are you saying you can't set the content of a webview from a background thread? The webview is created on the main thread and set to hidden and then I'm loading the content from a background thread. If this is wrong, what other way can this be done, or can it only be loaded on the main thread (which would ultimately slow down the UI while it loads).
Feb 23, 2011, 09:56 AM
You can't access the web view directly in a background thread. You can't access any UIView from a background thread. The web view loads asynchronously anyway so there's no benefit to accessing it from a background thread. If you're downloading content in a background thread you can then set the webview to load your local content from the main thread, once it's available. If you're using NSURLConnection to download content though there's not usually any reason to do that on a background thread either as it loads asynchronously anyway.
Feb 24, 2011, 11:25 AM
Thanks, that's what I decided to do, download and load it locally once it was available.