【问题标题】:Caching a UIWebView缓存 UIWebView
【发布时间】:2011-07-04 19:04:51
【问题描述】:

我对 iphone 开发非常陌生,我正在尝试获取一个 Web 视图以缓存到设备上,这样即使应用程序关闭它也会在那里停留,然后在应用程序再次启动时重新加载数据。我还希望它每 2 周重新加载缓存中的数据。

非常感谢, 托马斯

【问题讨论】:

  • 你可能不想缓存视图,但是数据(模型)
  • 好吧,我需要缓存视图,因为其中一个页面是 Web 视图并提供了大量信息,我希望它可以离线使用,而不是每次加载时都使用数据,但是也可以更新它而无需将更新推送到应用商店
  • 对最后一条评论感到抱歉(对编程来说真的很新(现在仍然是)),回头看看我知道我需要缓存网页而不是视图

标签: iphone caching uiwebview


【解决方案1】:

通过大量搜索和询问朋友,我设法找到了代码,尽管我会与大家分享

Objective-C

- (void) cacheFile
{
    //Create the file/directory pointer for the storage of the cache.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"cache.html"];

    //Check to see if a file exists a the location
    if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
       //Code for customising when the cache reloads would go here.
    }
    else
    {
        //If no file exists write the html cache to it
        //Download and write to file
        NSURL *cacheUrl = [NSURL URLWithString:@"INSERT WEB URL HERE"];
        NSData *cacheUrlData = [NSData dataWithContentsOfURL:cacheUrl];
        [cacheUrlData writeToFile:dataPath atomically:YES]; 
    }
//Run the load web view function.
[self loadWebView];
}


- (void) loadWebView
{
//Load up the web view from the cache.
[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:dataPath]]];

}

斯威夫特 3

func cacheFile() {
    //Create the file/directory pointer for the storage of the cache.
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    guard let dataPath = paths.first?.appending("cache.html") else {
        return
    }

    //Check to see if a file exists a the location
    if FileManager.default.fileExists(atPath: dataPath) {
        //Code for customising when the cache reloads would go here.
    } else if let cacheUrl = URL(string: "INSERT WEB URL HERE") {
        //If no file exists write the html cache to it
        //Download and write to file
        do {
            let cacheUrlData = try Data(contentsOf: cacheUrl)
            try cacheUrlData.write(to: URL(fileURLWithPath: dataPath), options: Data.WritingOptions.atomic)
        } catch {
            print("Problem with cacheUrlData")
        }
    }

    //Run the load web view function.
    loadWebView(dataPath: dataPath)
}

func loadWebView(dataPath: String) {
    webView.loadRequest(URLRequest(url: URL(fileURLWithPath: dataPath)))
}

【讨论】:

    猜你喜欢
    • 2011-07-25
    • 1970-01-01
    • 2012-02-21
    • 2013-09-07
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多