检索UIWebView缓存?

时间:2012-03-04 01:19:23

标签: ios uiwebview nsurlcache

我正在尝试使用以下代码确保我总是拥有最新的UIWebView缓存副本:

// Set URL to help file on server
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", HELP_FILE_URL]];

// Check network reachability
 wifiReach = [Reachability reachabilityWithHostName:[NSString stringWithFormat:@"%@", SERVER_URL]];
netStatus = [wifiReach currentReachabilityStatus];

// Start activity indicators
[self startAnimation];

// Verify current help file cache if we have network connection...
if (netStatus == ReachableViaWWAN || netStatus == ReachableViaWiFi) {

    helpFileRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:30];

} else {

    // Network NOT reachable - show (local) cache if it exists
    helpFileRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataDontLoad timeoutInterval:30];
}

// Show help file in a web view
[webView loadRequest:helpFileRequest];

在大多数情况下它工作正常,除非我在没有终止应用程序的情况下进入飞行模式。一旦进入飞行模式,缓存的webView就会显示出很好的但是UIWebView委托

(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

也被触发,我不想要。我只希望在缓存为空时触发它!我怎样才能做到这一点? (如果我终止应用程序它工作正常。)这是一个小细节,但我真的希望它能正常工作:)

1 个答案:

答案 0 :(得分:4)

好的 - 我通过识别UIWebView委托方法中的错误代码来解决它 - 见下文。我发现当缓存为空("资源不可用")时,错误代码为-1008,缓存中的数据为-1009(" Internet连接似乎处于脱机状态。" )。这两种情况都是离线的,在飞行模式下。

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"%@ : %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));

    [self stopAnimation];

    // No help to display - cache is empty and no Internet connection...
    if ([error code] == -1008) {
       NSString *alertMessage = @"To make Help available offline, you need to view it at least once when connected to the Internet.";
       UIAlertView *alertView = 
       [[UIAlertView alloc] initWithTitle:@"Help Unavailable"
                               message:alertMessage
                              delegate:nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
       [alertView show];
    }

    NSLog( @"Error code:%d, %@", [error code], [error localizedDescription]);
}