How to create then destroy a UIWebView inside a cl

2019-09-17 02:09发布

问题:

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?

回答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];   
});