简体   繁体   中英

How do I cache a file download request using Alamofire?

I have been trying to achieve caching of a file that I download from an url. File is about 5 MB in size. Below is the header that I obtain from that file 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

I am using following way to create download request:

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

File downloads successfully but, it isn't cached. When I go offline and try to download, I get ' The Internet connection appears to be offline. ' error.

I tried changing URLCache like below from AppDelegate didFinishLaunch

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

But no luck. Thanks in advance.

I think it is as simple as this:

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

where isNetwork is true if you detect a network is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM