本文介绍了阻塞主线程直到 UIWebView 完成加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图阻塞主线程直到 UIWebView 完成加载,但是在调用 [UIWebView loadRequest:] 之后调用 [NSThread sleepForTimeInterval:] 使加载永远不会完成: webViewDidFinishLoad 委托在睡眠结束后被调用.

I'm trying to block the main thread until a UIWebView finishes loading, but calling [NSThread sleepForTimeInterval:] after calling [UIWebView loadRequest:] makes the loading never complete: The webViewDidFinishLoad delegate is called after the sleep finishes.

为什么会这样?以及如何阻塞主线程?
我正在从 [ViewController willRotateToInterfaceOrientation:] 调用 loadPage,我想要做的是防止 iOS 界面旋转,直到加载具有其他方向的 webview.

Why is this happening? and How can I block the main thread?
I'm calling loadPage from [ViewController willRotateToInterfaceOrientation:], what I'm trying to do is to prevent the iOS interface to rotate until the webview with the other orientation is loaded.

- (void)loadPage {
    UIWebView* webview2 = [[UIWebView alloc] initWithFrame:rect];
    webview2.delegate = self;

    NSString* htmlPath = ..... ; // Path to local html file
    NSURL *newURL = [[[NSURL alloc] initFileURLWithPath: htmlPath] autorelease];
    NSURLRequest *newURLRequest = [[[NSURLRequest alloc] initWithURL: newURL] autorelease];

    [webview2 loadRequest:newURLRequest];
    [NSThread sleepForTimeInterval:10.0f]; // Why this blocks the uiwebview thread ??
    [self.view addSubview:webview2];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"Finished loading!");
}

推荐答案

我认为您在尝试解决错误的问题.

I think you're trying to solve the wrong problem.

你不想阻塞主线程.首先,整个 UI 是在主线程上绘制的,因此它看起来好像您的应用程序已挂起.其次,UIWebView 是 UI 的一部分(这可能是您所做的工作不起作用的原因).

You don't want to block the main thread. Firstly, the entire UI is drawn on the main thread, so it will appear as though your app has hung. Secondly, a UIWebView is part of the UI (which is probably why what you're doing doesn't work).

那么,该怎么办?

看看下面的方法:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

当您开始加载页面时,您可以从此方法返回 NO.加载完成后,您可以正常返回值.UIWebView 有一个告诉你状态的委托.

When you start loading your page you can return NO from this method. When it's finished loading you can return values normally. UIWebView has a delegate that tells you the status.

这篇关于阻塞主线程直到 UIWebView 完成加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:45
查看更多