问题
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