iOS Swift Alamofire cachePolicy

时间:2016-10-11 11:39:02

标签: ios swift alamofire

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?

感谢

1 个答案:

答案 0 :(得分:0)

这是我的工作代码。

    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,否则会从缓存中获取数据。