设备离线时使用 NSURLConnection 缓存

vti*_*tim 5 nsurlconnection offline-caching nsurlcache ios4 ios5

在 NSOperation 子类中,我使用以下代码从我们的服务器下载一个 xml 文件,然后对其进行解析:

NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15];
NSData * receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Run Code Online (Sandbox Code Playgroud)

我第二次发出同样的请求,服务器返回一个 HTTP 304,缓存的响应数据存储在receivedData. 到现在为止还挺好。

我的问题:当设备离线时是否有可能获得相同的缓存响应

El *_*ble 0

NSURLCache 不支持磁盘缓存。您可以简单地手动存储它或使用它: https: //github.com/steipete/SDURLCache

这是一个非常简单的缓存,可以完成它的工作...非常简单的用法,只有一个类...它也支持 etag。



    // Do this only once in your app...
    SDURLCache *urlCache = [[SDURLCache alloc] initWithMemoryCapacity:1024*1024   // 1MB mem cache
                                                         diskCapacity:1024*1024*5 // 5MB disk cache
                                                             diskPath:[SDURLCache defaultCachePath]];
    [NSURLCache setSharedURLCache:urlCache];
    [urlCache release];