我使用UIWebView加载HTML5应用程序的URL 我想要做的是缓存HTML文件,当没有网络连接时,它加载缓存 当连接可以使用时,它会再次加载URL以查看是否有新数据
答案 0 :(得分:0)
#define APP_PATH_HTML_PAGES_CACHE [[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"] stringByAppendingPathComponent:@"html_pages_cache"]
- (void)setUrlString:(NSString *)urlString{
if (![_urlString isEqualToString:urlString]) {
NSURL *url = nil;
_urlString = urlString;
NSString *fileName = [self fileNameFromUrl:_urlString];
if(isInternetConnected){//load page and store on file system
url = [NSURL URLWithString:_urlString];
[self downloadPageWithName:fileName andUrl:url];//download to cache
}else{
//network is not available, check for cached file
if ([self isFileExistInCacheDirectory:fileName]) {
url = [NSURL fileURLWithPath:[APP_PATH_HTML_PAGES_CACHE stringByAppendingPathComponent:fileName]];
}
else {
//TODO: show offline/error alert
}
}
//load local or remote page
// here url can point to local file or web page
NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
//to be sure that view components did initialized.
if ([self view]) {
[self.webView loadRequest:request];
}
}
- (void)downloadPageWithName:(NSString*)fileName andUrl:(NSURL*)url
{
`dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self checkIsCacheDirectoryExistOrCreate];`
NSString *filePath = [APP_PATH_HTML_PAGES_CACHE stringByAppendingPathComponent:fileName];
NSData *data = [NSData dataWithContentsOfURL:url];
[data writeToFile:filePath atomically:YES];
NSLog(@"Download: %@ -> %@", url.absoluteString, filePath);
});
}