设备离线时使用 NSURLConnection 缓存

发布于 2024-12-27 20:49:03 字数 544 浏览 3 评论 0原文

在 NSOperation 子类中,我使用以下代码从服务器下载 xml 文件,然后解析它:

NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15];
NSData * receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

第二次发出相同的请求时,服务器返回 HTTP 304,并存储缓存的响应数据在 receivedData 中。到目前为止,一切都很好。

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

In an NSOperation subclass, I am using the following code to download an xml-file from our server, and then later parse it:

NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15];
NSData * receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

The second time I make the same request, the server returns a HTTP 304, and the cached response data is stored in receivedData. So far so good.

My question: is it possible to get this same cached response when the device is offline?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2025-01-03 20:49:03

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];


NSURLCache does not support disk caching. You can simply store it manually or use this:
https://github.com/steipete/SDURLCache

It is very simple cache that does its job...very simple usage, only one class...It supports etags also.



    // 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];


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文