Why isn't UIWebView loading an NSURLRequest at applicationWillTerminate: in my app delegate?

457 views Asked by At

I am trying to clean up when the app is about to terminate/enter the background.

But, when the following code is called,

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSURL* url = [NSURL URLWithString:@"http://www.mysite.com/mobile/home?sysmethod=proclogout&systype=mobile&pagetype=jquerymobile"];
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:logoutURL]];
}

... the request starts loading, but never finishes. I read in Apple docs that apps have ~ 5 seconds to finish what they're doing once applicationWillTerminate: is called.

I don't believe the process is taking anywhere near that long, since I load this same request elsewhere in the app, and it always happens in mere milliseconds.

I have tried this both synchronously and asynchronously, with no luck either way.

Thanks for any thoughts!

1

There are 1 answers

1
Johannes Fahrenkrug On BEST ANSWER

Request loading in a UIWebView is asynchronous. That explains why the request begins to load but never finishes. If you want to make sure that a certain URL is called or loaded, you will have to somehow keep the applicationWillTerminate: method from exiting. If you don't need to really load the request in a web view, you could do use [NSURLConnection sendSynchronousRequest:returningResponse:error:] instead.

Also, a kind of hacky way to do it might be this:

[_webview stringByEvaluatingJavaScriptFromString:@"window.location.href=\"http://example.com/logout\""];

stringByEvaluatingJavaScriptFromString: is a blocking, synchronous method. I haven't tried, however, if it would really only return once the request is fully loaded. It might already return just after setting the location.