Skip to content

Instantly share code, notes, and snippets.

@antocara
Created March 14, 2022 13:06
Show Gist options
  • Save antocara/8a376cd4a89039d55e7b96c3fe7e6474 to your computer and use it in GitHub Desktop.
Save antocara/8a376cd4a89039d55e7b96c3fe7e6474 to your computer and use it in GitHub Desktop.
extension URLSession {
func handleTaskOrCache(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
let cachedDataForRequest = fetchCachedResponse(request: request)
guard let dateCache = dateFromResponse(cachedResponse: cachedDataForRequest) else {
handleDataTask(request: request, completionHandler: completionHandler)
return
}
if dateCache.isAllowRefreshDate(offsetTime: AppURLSession.shared.OFFSET_TIME_REFRESH_CACHE){
removeCachedFor(request: request)
handleDataTask(request: request, completionHandler: completionHandler)
}else{
completionHandler(cachedDataForRequest?.data, cachedDataForRequest?.response, nil)
}
}
private func handleDataTask(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void){
self.dataTask(with: request) { data, response, error in
completionHandler(data, response, error)
}.resume()
}
private func removeCachedFor(request: URLRequest){
URLSession.shared.configuration.urlCache?.removeCachedResponse(for: request)
}
private func fetchCachedResponse(request: URLRequest) -> CachedURLResponse?{
return URLSession.shared.configuration.urlCache?.cachedResponse(for: request)
}
private func dateFromResponse(cachedResponse: CachedURLResponse?) -> Date?{
return (cachedResponse?.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Date")?.formatResponseHeaderDate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment