2

我设置了 2 个 UIWebViews,第一个是控制第二个。他们通过 ajax 请求进行通信。

我想在第二个 WebView 中加载一个网站,然后继续执行其他任务。不幸的是,这正在崩溃。它正在崩溃,因为 Web 线程在收到响应后立即被第一个占用。第二种来不及加载网页,导致死锁。

我想延迟响应,直到第二个 WebView 完全加载网页。目前,第二个 WebView 在第一个 WebView 获取并响应后立即开始加载(即在 Web 线程被释放时)。

是否可以“暂停”/“暂停”当前(第一个 WebView)执行,直到第二个 WebView 完成加载?这意味着也开始执行第二个 WebView。

事件:

  1. 第一个 WebView 发送命令加载网页(使用同步 AJAX 命令)
  2. Web 线程被第一个 WebView 的任务阻塞
  3. 命令的执行和响应的计算
  4. 返回响应
  5. 第二个 WebView启动加载网页
  6. 僵局

我希望事件 5 在事件 4 之前。这可能吗?

解决方案: 正如您在评论中看到的那样,我通过使 then work concurrently解决了我的问题。基本上我不得不使用Grand Central Dispatch (GCD)另一种选择是使用NSOperationQueues来实现它它可以让您更好地控制执行流程,但实现起来往往更复杂。

有用的文献:

4

3 回答 3

4

现在,这可能需要一些调整,但它应该为您提供一个很好的起点。

基本上,我们创建一个并发 GCD 队列并调度 2 个异步调用来加载带有 2 个不同 URL 内容的 HTML 字符串。

当请求完成时,它们会将其 html 字符串加载到您的 Web 视图中。请注意,如果第二个 UIWebView 已经加载,第一个 UIWebView 只会加载其数据。

 __weak ViewController *bSelf = self;
dispatch_queue_t webQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(webQueue, ^{
    NSError *error;
    bSelf.html1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://google.com"] encoding:NSASCIIStringEncoding error:&error];
    if( !bSelf.secondLoaded)
    {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [bSelf.webView1 loadHTMLString:bSelf.html1 baseURL:nil];
        });
    }
});

dispatch_async(webQueue, ^{
    NSError *error;
    bSelf.html2 = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://amazon.com"] encoding:NSASCIIStringEncoding error:&error];
    bSelf.secondLoaded = YES;
    dispatch_sync(dispatch_get_main_queue(), ^{
        [bSelf.webView2 loadHTMLString:bSelf.html2 baseURL:nil];
        if( bSelf.html1 != nil )
        {
            [bSelf.webView1 loadHTMLString:bSelf.html1 baseURL:nil];
        }
    });

});
于 2013-04-12T20:07:45.477 回答
2

是的,最好的两种方法是使用Grand Central Dispatching (GCD)orNSOperationNSOperationQueue

对此的解释很长,但我会指导您阅读类似的内容。如果您在 google 中搜索这些术语,您可以找到很多其他资源。

于 2013-04-12T19:41:33.573 回答
0

你有没有尝试过这样的事情?

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.webView.delegate = self;
    self.webView2.delegate = self;

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"yourURL"]]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (webView == self.webView)
    {
        if (!self.webView.isLoading)
        {
            [self.webView2 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"yourURL"]]];
        }
    }
}
于 2013-04-12T18:47:47.017 回答