I'm trying to make sure that I always have an up to date cached copy of a UIWebView using the following code:
// 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];
It works fine in most cases except for when I go to Airplane mode without terminating the app. Once in Airplane mode the cached webView shows up fine BUT the UIWebView delegate
(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
is also triggered which I don't want. I only want that to be triggered if the cache is empty! How can I achieve that? (If I terminate the app it works fine.) It's a small detail but I really would like it to work correctly :)
OK - I solved it by identifying the error code in the UIWebView delegate method - see below. I found that the error code is -1008 when the cache is empty ("resource unavailable") and -1009 with data in the cache ("The Internet connection appears to be offline."). Both cases offline, in Airplane mode.
- (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]);
}