ios - 检索 UIWebView 缓存?

标签 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 委托(delegate)
(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

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

最佳答案

好的 - 我通过识别 UIWebView 委托(delegate)方法中的错误代码解决了它 - 见下文。我发现当缓存为空(“资源不可用”)时错误代码为-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]);
}

关于ios - 检索 UIWebView 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9551474/

相关文章:

ios - 社交媒体应用程序的最佳压缩质量?

ios - 从应用程序委托(delegate)暂停场景时 Spritekit 游戏崩溃

ios - IOS 7 中的 UIWebView 不能很好地处理 Twitter/Facebook 之类的网站(goBack/Forward 不起作用)

ios - 如何测试/检查 NSURLCache 的使用?

ios - 如何判断 NSURLCache 是否正常工作?

iphone - NSURLCache 缓存响应问题

ios - 使用相同的证书签名但错误 : Embedded binary is not signed with the same certificate

iphone - 任何 iOS block 的标识

ios - 让 UITextField 更改 Webview URL

ios - 如何通过 iOS 中的应用程序访问 UIAlertView 操作?