ios - 如何使用 Alamofire 缓存文件下载请求?

标签 ios swift alamofire nsurlcache

我一直在尝试实现从网址下载的文件的缓存。文件大小约为 5 MB。 下面是我从该文件 url 获取的 header :

Content-Type : application/x-zip-compressed
Content-Length : 4088083
Expires : Sun, 24 Jun 2018 20:10:51 GMT
Etag : "1e2ec46bcg24f13"
X-Powered-By : ASP.NET
Last-Modified : Thu, 22 Jun 2017 11:21:48 GMT
Accept-Ranges : bytes
Server : Microsoft-IIS/8.0
Date : Sat, 24 Jun 2017 20:10:48 GMT
Cache-Control : public,max-age=31536000

我使用以下方式创建下载请求:

var request = URLRequest(url: URL(string: downloadUrl)!, cachePolicy: URLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 120)
request.addValue("public", forHTTPHeaderField: "Cache-Control")

文件下载成功,但未缓存。当我离线并尝试下载时,出现“互联网连接似乎已离线。”错误。

我尝试从 AppDelegate didFinishLaunch 更改 URLCache,如下所示

let urlCache = URLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
URLCache.shared = urlCache

但运气不佳。 提前致谢。

最佳答案

我认为这很简单:

let request = isNetwork ? 
  NSURLRequest(url: downloadUrl! as URL):   
  NSURLRequest(url: downloadUrl! as URL,cachePolicy:.returnCacheDataDontLoad, timeoutInterval:1);

如果检测到网络可用,则 isNetwork 为 true。

关于ios - 如何使用 Alamofire 缓存文件下载请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740664/

相关文章:

ios - Swift 中强引用循环的混淆示例

ios - IOS 的 Facebook 应用内事件日志

ios - 在 UICollectionView 中重新加载数据后保持 collectionview 速度

ios - 滑动手势无法识别

ios - Obj-C block 作为参数

ios - 具有 self 类型转换的 Swift 通用扩展

swift - Iphone 7 和 iOS 10.1.1 上的谷歌地图无法正常工作

swift - 将 Alamofire 与 Yelp 搜索 API 结合使用

swift - 在使用 Alamofire 发出获取请求时,除了 `isSuccess` 之外,我还应该使用什么其他成员?

swift - 使用 Alamofire 将图像上传到 API 服务器