2016-12-21 36 views
0

我已经看到这个问题的几个职位,我不知道如何得到这个工作。例如,这篇文章NSCachedURLResponse returns object, but UIWebView does not interprets contentUIWebView NSURLCache加载离线数据

建议我们继承并覆盖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; 
    } 

} 

现在,当我加载通过web视图的要求,我下线,委托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. 击出了一些URL(可以说slickdeals.net)
  3. 转到离线杀死应用
  4. 启动应用程序
  5. UIWebView尝试打URL,但设备处于脱机状态,并返回返回缓存的响应。
  6. 我们显示缓存的响应。

任何想在我的代码中需要更改的想法是赞赏!

回答

0

NSURLCache设计用于HTTP一致性缓存,并且经常表现出令人意外的结果。您必须为自己的用例编写自己的缓存,并实现自定义的NSURLProtocol以使用它。该协议将响应放入缓存中,并在离线时从缓存中提供。罗布纳皮尔对此提出了一个excellent article