ios 从 SWIFT 中的 API 缓存 JSON 的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32242148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:25:00  来源:igfitidea点击:

Best way to Cache JSON from API in SWIFT?

iosjsonswiftcachingalamofire

提问by AruLNadhaN

I need to cache json data from API in swift. So I researched a Lot & get to this Post.

我需要快速缓存来自 API 的 json 数据。所以我研究了很多并找到了这篇文章

I tried to implement the Option 1 in my App. But the Custom manager always returned nil. I don't know why?

我试图在我的应用程序中实现选项 1。但是自定义管理器总是返回 nil。我不知道为什么?

After that I got AwesomeCache. It says that it an do Awesome API Caching. But I don't know how to implement this? I referred this Issue. Still I can't figure it Out.

之后我得到了AwesomeCache。它说它做了一个很棒的 AP​​I 缓存。但我不知道如何实现这个?我提到了这个问题。我还是想不通。

This is how my Current implementation Looks without Cache:

这是我的当前实现在没有缓存的情况下的外观:

Alamofire.request(.GET, "http://api.androidhive.info/volley/person_array.json")

    .responseJSON { (_, _, data, _) in
        let json = JSON(data!)
        let catCount = json.count
        for index in 0...catCount-1 {
            let name = json[index]["name"].string
            println(name)
         }

Please suggest me the Best way to Cache JSON from API ?

请建议我从 API 缓存 JSON 的最佳方法?

Thanks in Advance!

提前致谢!

UPDATE

更新

These are my requirements

这些是我的要求

  1. Fetch the JSON from the API & Parse the JSON data. These can be done with the help of Alamofire & SwiftyJSON

  2. I will populate the parsed data in the Table View. It works when the user is in Online.

  1. 从 API 获取 JSON 并解析 JSON 数据。这些可以在 Alamofire 和 SwiftyJSON 的帮助下完成

  2. 我将在表视图中填充解析的数据。当用户在线时它起作用。

But I want to show the data in the Table when the user is in offline too.

但是我也想在用户离线时显示表中的数据。

So I need to save the Parsed data or the JSON data in my cache & I need to refresh or expire the cache within a week or days.

所以我需要将解析后的数据或 JSON 数据保存在我的缓存中,我需要在一周或几天内刷新或过期缓存。

I don't prefer to store the JSON in my disk because it will be updated.

我不喜欢将 JSON 存储在我的磁盘中,因为它将被更新。

Please suggest me the Best way to achieve this...

请建议我实现这一目标的最佳方法......

回答by cnoon

You have many tools already at your disposal.

您已经拥有许多可供使用的工具。

NSURLCache

网址缓存

All your requests are already stored in the NSURLCachein the NSURLSessionConfigurationon the NSURLSessionstored inside the sharedInstanceof the Alamofire Manager. Those stored requests already follow all the caching policy rules provided by the servers you are hitting. You can control the caching behavior by setting the requestCachePolicyon your own custom NSURLSessionConfiguration. I'd also suggest you read through this awesome NSHipster article that walks you through the ins and outs of NSURLCacheand how to control it.

您所有的请求都已经存储在NSURLCacheNSURLSessionConfigurationNSURLSession存储在里面sharedInstance的Alamofire的Manager。那些存储的请求已经遵循您正在访问的服务器提供的所有缓存策略规则。您可以通过requestCachePolicy在您自己的自定义NSURLSessionConfiguration上设置 来控制缓存行为。我还建议你通读这篇很棒的 NSHipster 文章,它会引导你了解NSURLCache 的来龙去脉以及如何控制它。

Creating custom Managerobjects is covered in the current Alamofire docs.

Manager当前的 Alamofire文档中介绍了如何创建自定义对象。

Downloading JSON to Disk

将 JSON 下载到磁盘

You can also download the JSON directly to disk using Alamofire.downloadinstead of using Alamofire.request. This will download the payload to a fileURLthat you provide in the destinationclosure. This would give you full control over the caching of the file after that point. You would need to create your own caching policy around these files afterwards if you wanted to follow the caching header rules provided by the server.

您还可以使用Alamofire.download而不是使用将 JSON 直接下载到磁盘Alamofire.request。这会将有效负载下载到fileURL您在destination闭包中提供的a 。这将使您完全控制在那之后文件的缓存。如果您想遵循服务器提供的缓存标头规则,则需要在之后围绕这些文件创建自己的缓存策略。

Populating Table View

填充表视图

Once you have your data downloaded to disk, you need to load it into an NSDatablob and parse it into JSON to populate your table view. This should be pretty straight forward. You need the destination NSURLthat you specified to Alamofire when you started your download. Then load the file data into an NSData blob. Finally, use NSJSONSerialization to convert the NSDataobject into a JSON AnyObjectwhich can be parsed into model objects to populate your table view.

将数据下载到磁盘后,您需要将其加载到NSDatablob 中并将其解析为 JSON 以填充表视图。这应该很简单。您需要在NSURL开始下载时为 Alamofire 指定的目的地。然后将文件数据加载到 NSData blob 中。最后,使用 NSJSONSerialization 将NSData对象转换为AnyObject可以解析为模型对象以填充表视图的 JSON 。

Obviously you don't "have" to parse the JSON into model objects, but this helps protect your table view from malformed JSON data.

显然,您不必“必须”将 JSON 解析为模型对象,但这有助于保护您的表视图免受格式错误的 JSON 数据的影响。

Storing JSON for Offline Usage

存储 JSON 以供离线使用

If you stick with this approach, you'll need to track your cache expiration dates in something like CoreData or SQLite. You can do this by either caching the paths to the JSON files on disk, or store the model objects directly in CoreData or SQLite. This could get fairly complicated and I would not recommend this approach unless you absolutely don't want to cache your model objects.

如果您坚持使用这种方法,您将需要在 CoreData 或 SQLite 之类的东西中跟踪您的缓存到期日期。您可以通过将 JSON 文件的路径缓存在磁盘上,或将模型对象直接存储在 CoreData 或 SQLite 中来实现。这可能会变得相当复杂,除非您绝对不想缓存模型对象,否则我不会推荐这种方法。

Offline Usage

离线使用

Generally, if you need to cache data for offline usage, you want to store your model objects in something like CoreData. You would use the Alamofire requestmethod coupled with a responseJSONserializer to parse the data into JSON. Then you would convert the JSON into model objects. From there, you'd save your model objects in CoreData, then finally populate your table view with the model objects.

通常,如果您需要缓存数据以供离线使用,您希望将模型对象存储在 CoreData 之类的东西中。您可以使用 Alamofirerequest方法和responseJSON序列化程序将数据解析为 JSON。然后您将 JSON 转换为模型对象。从那里,你将你的模型对象保存在 CoreData 中,然后最后用模型对象填充你的表视图。

The nice thing about this approach is that you have all your model objects cached in the case that your table view is accessed when the device is offline. Coupling this design with queries to your NSURLCacheto see if your request is cached let's you avoid unnecessary server calls and parsing logic when you already have your model objects generated.

这种方法的好处是,在设备离线时访问表视图的情况下,您可以缓存所有模型对象。将此设计与对您的查询相结合,NSURLCache以查看您的请求是否已缓存,这样您就可以在已经生成模型对象时避免不必要的服务器调用和解析逻辑。

Given the updates to your original question, I would recommend this approach.

鉴于您的原始问题的更新,我会推荐这种方法。

回答by huync

You can use this cache open source. It cache data on disk and memory. Can cache many swift type, and custom class which inherit NSObject and conform NSCoding protocol.

你可以使用这个缓存开源。它将数据缓存在磁盘和内存上。可以缓存很多 swift 类型,以及继承 NSObject 并符合 NSCoding 协议的自定义类。

https://github.com/huynguyencong/DataCache

https://github.com/huynguyencong/DataCache

To implement: First, it use NSCache for mem cache. NSCache use like a dictionary. Second, save cache to disk, use NSFileManager methods.

实现:首先,它使用 NSCache 作为内存缓存。NSCache 像字典一样使用。其次,将缓存保存到磁盘,使用 NSFileManager 方法。