In Alamofire
version 3 I use NSURLRequest.CachePolicy.returnCacheDataDontLoad
for request cache
let URLRequest = NSMutableURLRequest(url: URL(string: url)!)
URLRequest.cachePolicy = NSURLRequest.CachePolicy.returnCacheDataDontLoad
Alamofire.request(URLRequest){...}
But how can I use cachePolicy in Alamofire 4 and swift 3?
thanks
I searched everywhere and ended up with this :
let TheURL = DEFAULT_APP_URL + "api/getList?Id="+ID
let urlString = NSURL(string: TheURL)
var mutableURLRequest = URLRequest(url: urlString! as URL)
mutableURLRequest.httpMethod = "GET"
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.cachePolicy = NSURLRequest.CachePolicy.returnCacheDataElseLoad
Alamofire.request(mutableURLRequest)
.responseJSON
{....}
Here is my piece of working code.
private static func request(_ showHud: Bool = true, urlString: String,
httpMethod: HTTPMethod,
parameters: [String : Any] = [:],
headers: [String : Any] = [:],
success : @escaping SuccessBlock,
failure : @escaping ErrorBlock) {
var additionalHeaders: HTTPHeaders?
additionalHeaders = headers as? HTTPHeaders
guard let url = URL(string: urlString) else { return }
var urlRequest = URLRequest(url: url)
if !(NetworkReachabilityManager()?.isReachable ?? false) {
urlRequest.cachePolicy = .returnCacheDataDontLoad
} else {
showIndicator(showHud)
}
urlRequest.allHTTPHeaderFields = additionalHeaders
urlRequest.httpMethod = httpMethod.rawValue
do {
urlRequest = httpMethod == .get ? try URLEncoding.default.encode(urlRequest, with: parameters) : try JSONEncoding.default.encode(urlRequest, with: parameters)
} catch {
failure(NSError(localizedDescription: "Something went wrong!"))
}
Alamofire.request(urlRequest).responseObject { (response: DataResponse<ResponseHandler>) in
parseResponse(response, success: success, failure: failure)
}
}
The key is before loading data from cache I checked for internet connectivity. If internet is available I show the loader and it loads the api and if not it gives me data from cache.
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.