0

I am trying to dynamically create a UIWebView inside a class file upon launching the application.

I have successfully gotten a function to be called inside that class file upon launching, but when I add the the code to create the webview to that function, I am getting errors like this: "Tried to obtain the web lock from a thread other than the main thread or web thread. This may be the result of calling to UIKit from a secondary thread. Crashing now..."

My code to create the UIWebView is this:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
[webView setDelegate:self];
[webView setHidden:YES];
NSURL *url = [NSURL URLWithString:address];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];

Where am I going wrong?

ccagle8
  • 308
  • 1
  • 2
  • 12

1 Answers1

1

You are creating the webview from a background thread, which is not allowed by Apple and makes your app crash.
You should use dispatch_async to create your webview from the main thread :

dispatch_async(dispatch_get_main_queue(), ^{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
    [webView setDelegate:self];
    [webView setHidden:YES];
    NSURL *url = [NSURL URLWithString:address];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [webView loadRequest:urlRequest];   
});
nicolasthenoz
  • 1,852
  • 1
  • 13
  • 14
  • Thanks! That did it, but now I am getting a different error on `[webView setDelegate:self`] - **Incompatible pointer types sending 'const Class' to paramter of type 'id''** – ccagle8 Sep 19 '12 at 14:02
  • I have to assume you call this method from within a class method `+(void) yourMethodToCreateTheWebview`. Therefore, setting the delegate to self can't work... You have to instanciate an object to use it as a delegate – nicolasthenoz Sep 19 '12 at 14:06
  • So I just removed that line and now everything works error free... Thank you very much nicolasthenoz!! – ccagle8 Sep 19 '12 at 14:26
  • No worry but note that you might need a delegate to know when the webview is done loading for example... – nicolasthenoz Sep 19 '12 at 14:28
  • I am just curious, as if you can extend this class, and make a "Class Delegate", to call it once the loadView is completed? Shouldn't that work as a workaround? – topgun Nov 26 '12 at 18:30