Block main thread until UIWebView finishes loading

风格不统一 提交于 2019-12-24 02:22:27

问题


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.

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!");
}

回答1:


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

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).

So, what to do?

Have a look at the following method:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

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.




回答2:


Have a look at the class reference for NSURLRequest, there is a sync method in there.

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error


来源:https://stackoverflow.com/questions/10484629/block-main-thread-until-uiwebview-finishes-loading

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