NSURLRequest cachePolicy and connection in UIWebView

跟風遠走 提交于 2020-01-07 08:29:30

问题


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

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