问题
I set up a UIWebView with a cachePolicy of NSURLRequestReloadIgnoringLocalAndRemoteCacheData, and everything was fine: when there was a connection, the UIWebView loaded, and when there wasn't, connection:didFailWithError: was called and I got my UIAlertView.
But when I change the cachePolicy to NSURLRequestReturnCacheDataElseLoad (which is the policy I actually want), in the absence of a connection, the cached page loads and then, when I click on a link...nothing happens. No connection:didFailWithError: called. No UIAlertView.
How do I fix this?
EDIT: Perhaps I have the beginning of an answer.... I can at least identify when a link in the UIWebView is clicked, using the following method:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)req navigationType: (UIWebViewNavigationType)navigationType
{
if (navigationType==UIWebViewNavigationTypeLinkClicked)
{
NSLog(@"Blah!");
}
return YES;
}
Now, instead of NSLogging "Blah!" I just need to get it to call connection:didFailWithError.
So how do I do that?
回答1:
I did it!
I added this code:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)req navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType==UIWebViewNavigationTypeLinkClicked)
{
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.homePageOfTheApp.com"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error title." message:@"Error message." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
Though I might replace http://www.homePageOfTheApp.com"
with http://www.google.com
since, even though my host has very reliable servers, I'm going to guess that Google's are even better....
来源:https://stackoverflow.com/questions/12102017/nsurlrequest-cachepolicy-and-connection-in-uiwebview