Search code examples
swiftalamofire

Alamofire callback caching


I've been thinking of using Alamofire for my network requests. I've read somewhere that Alamofire does callback caching. What I mean by that is when I do multiple GETs to the same URL, but only 1 does the actual request and both just receive the response. This way I could avoid multiple network calls to same resource, but have the resource in both callbacks

I just cannot find any truth of this concept in their documentation.

So my question is this possible? And if so is this just a behind the scene thing or how do I use it?

I've been testing with the following code from their documentation:

func x() {
    Alamofire.request("https://httpbin.org/get").responseJSON { response in
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")                         // response serialization result
        print("Timeline: \(response.timeline)")

        if let json = response.result.value {
            print("JSON: \(json)") // serialized json response
        }

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)") // original server data as UTF8 string
        }
    }
}

x()
x()
x()

Method x is called 3 times and 3 GET's are fired over the network.


Solution

  • I'm not sure what you've read, but Alamofire doesn't have any sort of request deduplication. AlamofireImage does, for image requests, but the feature only exists in that library. However, Alamofire does support standard HTTP caching methods, so if you request the same resource twice, and the server properly returned one of the caching headers, Alamofire should accept the locally cached copy. This is done through the standard URLCache class, so you should read its documentation to learn more.