1

我正在尝试使用以下代码确保我始终拥有 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

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

4

1 回答 1

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]);
}
于 2012-03-05T14:35:24.490 回答