Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何缓存html5文件(UIWebView)_Ios_Uiwebview - Fatal编程技术网

Ios 如何缓存html5文件(UIWebView)

Ios 如何缓存html5文件(UIWebView),ios,uiwebview,Ios,Uiwebview,我使用UIWebView加载作为HTML5应用程序的URL。 我要做的是缓存HTML文件,当没有网络连接时,它会加载缓存。 当连接可以使用时,它会再次加载URL以查看是否有新数据您可以尝试以下操作: #define APP_PATH_HTML_PAGES_CACHE [[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"] stringByAppendingPathComponent:@"html_pages_ca

我使用UIWebView加载作为HTML5应用程序的URL。
我要做的是缓存HTML文件,当没有网络连接时,它会加载缓存。

当连接可以使用时,它会再次加载URL以查看是否有新数据

您可以尝试以下操作:

#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);
});

}

您可能想看看HTML“脱机应用程序”如何使用urlString?例如,当我第一次启动应用程序时,它缓存第一页,然后我终止应用程序。(urlString已被销毁),然后我再次启动应用程序,如果第一页发生更改,它将再次加载url,或者它只是加载缓存,如果网络连接可用,则提供一段代码在文件系统上缓存页面;如果没有internet,则从文件系统加载页面。