简体   繁体   English

如何使用 Alamofire 从缓存和网络加载数据?

[英]How to load data BOTH from cache and from network using Alamofire?

I'm trying to use caching to make my iOS app more snappy.我正在尝试使用缓存来使我的 iOS 应用程序更加活泼。 What I would like to do for every request is to:我想为每个请求做的是:

  1. return data from cache if present如果存在,则从缓存中返回数据
  2. if connected to the internet, load data from API in the background如果连接到互联网,在后台从 API 加载数据
  3. if data from API is different from what was already in the cache, update the cache and return that data again so that the UI can be refreshed如果来自 API 的数据与缓存中已有的数据不同,请更新缓存并再次返回该数据,以便刷新 UI

I'm aware that if there is already some data in the cache and I'm connected to the Internet, there could be 2 successive calls to my response code, but that's what I want: the first set of data, potentially out-of-date returned from the cache gives me something right away, and the second set of data makes sure everything is up-to-date.我知道如果缓存中已经有一些数据并且我已连接到 Internet,则可能会连续 2 次调用我的响应代码,但这就是我想要的:第一组数据,可能超出- 从缓存返回的日期立即给了我一些东西,第二组数据确保一切都是最新的。

All the caching approaches I have used so far only let me implement an EITHER/OR approach solely based on cache age.到目前为止,我使用的所有缓存方法都只让我实现仅基于缓存年龄的 EITHER/OR 方法。 Right now, I'm using AlamofireURLCache5 .现在,我正在使用AlamofireURLCache5 Is it possible to implement such a cache with Alamofire 5 or do I have to implement it manually?是否可以使用 Alamofire 5 实现这样的缓存,还是必须手动实现?

EDIT: I've been told what I am trying to do is called a Stale-While-Revalidate sort of cache.编辑:我被告知我正在尝试做的称为 Stale-While-Revalidate 类型的缓存。

Alamofire only supports URLCache and the functionality provided by URLSession . Alamofire 仅支持URLCacheURLSession提供的功能。 You can implement equivalent patterns above Alamofire, perhaps in a type that keeps the last successful value while updating from the network.您可以在 Alamofire 之上实现等效的模式,也许是在从网络更新时保留最后一个成功值的类型。

As an aside, you probably don't want your "if connected to internet" condition.顺便说一句,您可能不想要“如果连接到互联网”的条件。 Instead you should just request the resource and update if it succeeds.相反,您应该只请求资源并在成功时更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM