The underlying URLSession utilises a URLCache. Ensure your URLSession uses a URLCache and your server uses an appropriate response to instruct the client to cache the response.
In order to get the cached response, if any, the method according HTTP would be to set a cache control request header:
Cache-Control: only-if-cached
(see RFC 5.2.1.7 only-if-cached)
That is, you would need to set this additional header when you create the request. Then execute the request as usual and you would either get the cached response or a status code 504 if there is none. Exactly what you would need.
Now, when you try this you realise, it unfortunately won't work as expected (bummer!). The reasons for this is manifold and it would be futile to go into detail.
The approach you may try next is to set the cache control policy of the URLRequest as follows:
urlRequest.cachePolicy = .returnCacheDataDontLoad
You can look up the meaning of it here: returnCacheDataDontLoad
Please read the documentation and the source documentation as well carefully, since it's not implemented in every iOS version!
That seems to be a working solution, however when using Alamofire you need to access the underlying URLRequest in order to set the cache policy (you may search on SO how to accomplish this) - and you need to be sure Alamofire does not alter your cache policy under the hood.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…