【问题标题】:How to create then destroy a UIWebView inside a class file如何在类文件中创建然后销毁 UIWebView
【发布时间】:2012-09-11 20:03:54
【问题描述】:

我正在尝试在启动应用程序时在类文件中动态创建 UIWebView。

我已经成功地在启动时在该类文件中调用了一个函数,但是当我将创建 webview 的代码添加到该函数时,我收到如下错误:“试图获取网络从主线程或 Web 线程以外的线程锁定。这可能是从辅助线程调用 UIKit 的结果。现在崩溃..."

我创建 UIWebView 的代码是这样的:

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

我哪里错了?

【问题讨论】:

  • 这个sn-p在什么方法里面?

标签: objective-c ios xcode uiwebview uiwebviewdelegate


【解决方案1】:

您正在从后台线程创建 web 视图,这是 Apple 不允许的,并且会使您的应用程序崩溃。
你应该使用 dispatch_async 从主线程创建你的 webview:

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

【讨论】:

  • 谢谢!做到了,但现在我在[webView setDelegate:self] 上遇到了另一个错误 - 不兼容的指针类型将“const Class”发送到“id”类型的参数'
  • 我必须假设您从类方法+(void) yourMethodToCreateTheWebview 中调用此方法。因此,将委托设置为 self 不起作用...您必须实例化一个对象才能将其用作委托
  • 所以我刚刚删除了该行,现在一切正常无误......非常感谢nicolasthenoz!
  • 不用担心,但请注意,您可能需要委托来知道 webview 何时完成加载...
  • 我只是很好奇,好像你可以扩展这个类,并制作一个“Class Delegate”,在loadView完成后调用它?这不应该作为一种解决方法吗?
猜你喜欢
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 2012-11-17
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
相关资源
最近更新 更多