How to create then destroy a UIWebView inside a class file

痴心易碎 提交于 2020-01-06 06:49:10

问题


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


来源:https://stackoverflow.com/questions/12495966/how-to-create-then-destroy-a-uiwebview-inside-a-class-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!