Based on @fredpi answer, I slightly improved caching plugin for Moya. Below is my version:
import Foundation
import Moya
protocol CachePolicyGettable {
var cachePolicy: URLRequest.CachePolicy { get }
}
final class NetworkDataCachingPlugin: PluginType {
init (configuration: URLSessionConfiguration, inMemoryCapacity: Int, diskCapacity: Int, diskPath: String?) {
configuration.urlCache = URLCache(memoryCapacity: inMemoryCapacity, diskCapacity: diskCapacity, diskPath: diskPath)
}
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
if let cacheableTarget = target as? CachePolicyGettable {
var mutableRequest = request
mutableRequest.cachePolicy = cacheableTarget.cachePolicy
return mutableRequest
}
return request
}
}
extension NetworkApiService: CachePolicyGettable {
var cachePolicy: URLRequest.CachePolicy {
switch self {
case .getUserProfile:
return .returnCacheDataElseLoad
default:
return .useProtocolCachePolicy
}
}
}
In order to clear the cache, you need to have an access to urlRequest object/objects. How to retrieve an urlRequest for Moya route you can find in the following topic.
To clear the cache you can use following code:
public func clearCache(urlRequests: [URLRequest] = []) {
let provider = ... // your Moya provider
guard let urlCache = provider.manager.session.configuration.urlCache else { return }
if urlRequests.isEmpty {
urlCache.removeAllCachedResponses()
} else {
urlRequests.forEach { urlCache.removeCachedResponse(for: $0) }
}
}