怎样用Alamofire缓存网络请求到的数据?

我努力缓存通过一个URL下载到的数据文件,文件大约有5M。
我获取文件的URL请求头如下:

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")

下载文件很顺利,但没有缓存成功。
我尝试离线下载,显示错误:

The Internet connection appears to be offline

我试过在AppDelegatedidFinishLaunching方法中修改URLCache,如下:

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

但没什么作用。
怎样用Alamofire缓存呢?

阅读 6.1k
2 个回答
    Alamofire.request(req)
        .response {(request, res, data, error) in
            let cachedURLResponse = NSCachedURLResponse(response: res!, data: (data as NSData), userInfo: nil, storagePolicy: .Allowed)
            NSURLCache.sharedURLCache().storeCachedResponse(cachedURLResponse, forRequest: request)
        }
let request = isNetwork ? 
  NSURLRequest(url: downloadUrl! as URL):   
  NSURLRequest(url: downloadUrl! as URL,cachePolicy:.returnCacheDataDontLoad, timeoutInterval:1);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题