Created
March 14, 2022 13:06
-
-
Save antocara/8a376cd4a89039d55e7b96c3fe7e6474 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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