I need the API responses to be cached for a longer duration. Hence, I am trying to modify the 'max-age' header for the API response.
But the
urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?
) -> Void)
method is not called to be able to do it.
API Client Class code :
public class APIClient: NSObject, URLSessionDelegate {
var endPoint: String!
var urlSession: URLSession!
public init(urlSession: URLSession = .shared) {
super.init()
self.endPoint = endPoint
let sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.requestCachePolicy = .returnCacheDataElseLoad
sessionConfiguration.urlCache = .shared
self.urlSession = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
if dataTask.currentRequest?.cachePolicy == .useProtocolCachePolicy {
let newResponse = proposedResponse.response(withExpirationDuration: 60)
completionHandler(newResponse)
}else {
completionHandler(proposedResponse)
}
}
private func dispatch<ReturnType: Decodable>(request: URLRequest) -> AnyPublisher<ReturnType, NetworkError> {
let url = request.url // For troubleshooting only
return urlSession
.dataTaskPublisher(for: request)
// Map on Request response
.tryMap({ data, response in
return data
})
.decode(type: ReturnType.self, decoder: JSONDecoder())
.mapError { error in
}
.eraseToAnyPublisher()
}
}
API call:
func makeAPICall() -> AnyPublisher<ContentConfigResponseModel, NetworkError> {
var request = // create request data
let apiClient = APIClient(endPoint: request.path)
return apiClient.dispatch(request)
}
I have with tried multiple cachePolicy. According to some suggestions I have tried implementing
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) async -> URLSession.ResponseDisposition {
return URLSession.ResponseDisposition.allow
}