在Alamofire版本3中,我将NSURLRequest.CachePolicy.returnCacheDataDontLoad用于请求缓存
let URLRequest = NSMutableURLRequest(url: URL(string: url)!)
URLRequest.cachePolicy = NSURLRequest.CachePolicy.returnCacheDataDontLoad
Alamofire.request(URLRequest){...}但是如何在Alamofire 4和swift 3中使用cachePolicy呢?
谢谢
发布于 2017-05-08 22:10:15
我找遍了所有地方,最后得到了这个:
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
{....}发布于 2018-12-20 18:40:12
这是我的一段工作代码。
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)
}
}关键是在从缓存加载数据之前,我检查了互联网连接。如果互联网可用,我显示加载器,它加载api,如果没有,它从缓存中给我数据。
https://stackoverflow.com/questions/39976416
复制相似问题