【问题标题】:UIWebView NSURLCache load data for offlineUIWebView NSURLCache 离线加载数据
【发布时间】:2016-12-21 02:10:25
【问题描述】:

我已经看过几个关于这个问题的帖子,但我不知道如何让它发挥作用。比如这个帖子NSCachedURLResponse returns object, but UIWebView does not interprets content

建议我们在返回缓存响应之前继承并覆盖 cachedResponseForRequest 并修改 NSURLRequest(不确定为什么需要这样做)。

这是我在NSURLCache 子类中的代码:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {

    NSCachedURLResponse *resp = [super cachedResponseForRequest:request];
    if (resp != nil && resp.data.length > 0) {
        NSDictionary *headers = @{@"Access-Control-Allow-Origin" : @"*", @"Access-Control-Allow-Headers" : @"Content-Type"};
        NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:headers];
        NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:resp.data];
        return cachedResponse;
    } else {
        return nil;
    }

}

现在,当我通过 webview 加载请求并且我处于脱机状态时,委托 didFailLoadWithError 被调用(它无法加载),但在调用该委托方法之前,我的 cachedResponseForRequest 方法被调用并缓存的响应有一些 html 但是我的 didFailLoadWithError 方法仍然被调用。所以我的问题是,如果我们从NSURLCache 返回缓存的响应,是否应该调用webViewDidFinishLoad,如果不是,我该如何进行这项工作?

我的didFinishLaunchingWithOptions 中有这个:

NSUInteger cacheSizeMemory = 500*1024*1024; // 500 MB
NSUInteger cacheSizeDisk = 500*1024*1024; // 500 MB
NSURLCache *sharedCache = [[CustomCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];

这是我想要工作的流程:

  1. 启动应用程序。
  2. 点击一些网址(比如说 slickdeals.net)
  3. 脱机杀死应用程序
  4. 启动应用程序
  5. UIWebView 尝试点击 url 但设备处于离线状态并返回返回的缓存响应。
  6. 我们显示缓存的响应。

对我的代码需要更改的任何想法表示赞赏!

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    NSURLCache 是为符合 HTTP 的缓存而设计的,并且经常出现意外行为。您必须为您的用例编写自己的缓存,并实现自定义NSURLProtocol 才能使用它。该协议将响应放入您的缓存中,并在离线时从缓存中提供它们。 Rob Napier 就此写了一封excellent article

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      相关资源
      最近更新 更多