【问题标题】:How can I add HTTP request caching to an application using ASIHTTPRequests?如何使用 ASIHTTPRequests 将 HTTP 请求缓存添加到应用程序?
【发布时间】:2009-12-05 23:20:18
【问题描述】:
我在 iphone 应用程序中使用 ASIHttpRequests 和 ASINetworkQueue 从 Web 服务中检索大约 100k XML 文件和大量缩略图。我想以NSURLCache 的样式缓存请求。 ASI 似乎不支持缓存,我查看了代码并使用 C 来创建请求,因此插入 NSURLCache 层似乎很棘手。
实现这一点的最佳方法是什么?
【问题讨论】:
标签:
iphone
ios
asihttprequest
【解决方案1】:
ASIHTTPRequest 现在支持缓存 - 查看 ASIownloadCache 即。
[ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]
【解决方案2】:
您可以在进入 ASI 代码之前提供自己的缓存。
将您的 ASI 代码包装在具有方法的类中:
-(NSString *)getContentFor:(NSURL *)url
该方法首先检查内部 NSDictionary 以查看它是否具有指定 url 的键。如果是,则返回与密钥一起存储的对象。
如果没有,它会执行正常的 ASIRequest。当从服务器接收到请求时,它会将其作为字符串存储在您的字典中,并带有 url 的键。
当然,您需要小心处理异步请求和旧请求过期。
【解决方案3】:
任何询问他们如何直接使用 ASIHTTPRequest 执行此操作的人可能会对添加对此功能的支持作为选项的代码的 branch 感兴趣。
【解决方案4】:
NSURLConnection 支持 NSURLCache 风格的缓存,它在幕后为你做了很多工作。它甚至有一个很好的委托方法,可以让你操作缓存的响应:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
【解决方案5】:
试试这个,它对我有用。
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy];
[request setSecondsToCache:60*60*24]; // Cache for 24 hrs
[request setDelegate:self]; // A delegate must be specified
[request setCompletionBlock:^{