【问题标题】:How to cache websites in UIWebView correctly?如何在 UIWebView 中正确缓存网站?
【发布时间】:2016-09-28 07:31:30
【问题描述】:

我有一个UISwitch,如果它处于活动状态,我的UIWebView 应该会缓存所有访问过的网站。

如果它处于活动状态,我有以下代码

[[NSURLCache sharedURLCache] setDiskCapacity:4 * 1024 * 1024];
[[NSURLCache sharedURLCache] setMemoryCapacity:32 * 1024 * 1024];
[self setRequestObj:[NSURLRequest requestWithURL:loadUrl cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0]];

如果我停用了我的 UISwitch 我的代码,请执行以下操作

[[NSURLCache sharedURLCache] setDiskCapacity:0];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[self setRequestObj:[NSURLRequest requestWithURL:loadUrl]];

有什么方法我必须激活它才能正常工作吗?如果它被关闭,它应该在每次调用时从 Web 服务器加载所有内容。如果它已打开,如果他之前访问过它,它应该从他的缓存中加载所有内容。

如果我关闭应用程序并再次打开它并且我的Button 仍然打开,似乎没有缓存,尽管我在关闭应用程序时没有删除它。

如果理解起来很复杂,抱歉;)。

【问题讨论】:

    标签: ios caching uiwebview


    【解决方案1】:

    你可以试试这个,

       // Determile cache file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];   
    
    // Download and write to file
    NSURL *url = [NSURL URLWithString:@"http://www.google.co.uk"];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    [urlData writeToFile:filePath atomically:YES];
    
    // Load file in UIWebView
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    

    您可以参考this answer了解更多详情。

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      相关资源
      最近更新 更多