请求正文更改时进行Alamofire缓存

时间:2019-04-18 15:58:32

标签: swift caching alamofire

我正在使用Alamofire进行网络请求,并启用了缓存。现在它的工作方式是,如果一个请求的url与过去使用的请求相同(在缓存时间间隔内),它将从磁盘而不是从远程服务器检索数据。

我想对此进行更改,以便如果url相同但body不同,则应将其视为新请求。

delegate.dataTaskWillCacheResponseWithCompletion = { session, datatask, cachedResponse, completion in
    if let response = cachedResponse.response as? HTTPURLResponse,
        var headers = response.allHeaderFields as? [String: String] {

        if isCachable {
            headers[HTTPHeaderKeys.CacheControl] = "max-age=\(cacheDuration)"
            print("GET CACHED RESPONSE: \(String(describing: response.url))")
        } else {
            headers[HTTPHeaderKeys.CacheControl] = "no-store"
        }

        let modifiedResponse = HTTPURLResponse(url: response.url!,
                                               statusCode: response.statusCode,
                                               httpVersion: ServiceConstants.HTTP_VERSION,
                                               headerFields: headers)
        let modifiedCachedResponse = CachedURLResponse(response: modifiedResponse!,
                                                       data: cachedResponse.data,
                                                       userInfo: cachedResponse.userInfo,
                                                       storagePolicy: cachedResponse.storagePolicy)

        completion(modifiedCachedResponse)
    }
}

0 个答案:

没有答案