Search code examples
swiftalamofiremoya

Cache Handling with Moya


We have implemented Moya, RxSwift And Alamofire as pods in our project.

Does anyone know how you gain control of the cache policies per url request using this tech?

I have read through quite a few of the issues on Moya's GitHub page but still can't find anything. Also tried using actual json response stored as files for the sampleData like so:

var sampleData: Data {
    guard let path = Bundle.main.path(forResource: "SampleAggregate", ofType: "txt") else {
        return "sampleData".utf8Encoded
    }
    let sample = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
    return sample!.utf8Encoded

}

Thanks in advance for any pro tips :)


Solution

  • Subclass MoyaProvider and compose requestClosure.

    It should look something like:

    final class MyProvider<Target: TargetType>: MoyaProvider<Target> {
    
        public init(
            endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
            requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
            stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
            manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(),
            plugins: [PluginType] = [],
            trackInflights: Bool = false
        ) {
            super.init(
                endpointClosure: endpointClosure,
                requestClosure: { endpoint, closure in
                    var request = try! endpoint.urlRequest() //Feel free to embed proper error handling
                    if request.url == URL(string: "http://google.com")! {
                        request.cachePolicy = .returnCacheDataDontLoad
                    } else {
                        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
                    }
                    closure(.success(request))
                },
                stubClosure: stubClosure,
                manager: manager,
                plugins: plugins,
                trackInflights: trackInflights
            )
        }
    
    }