在SWIFT中从API缓存JSON的最佳方法? [英] Best way to Cache JSON from API in SWIFT?

查看:193
本文介绍了在SWIFT中从API缓存JSON的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在swift中缓存来自API的json数据。
所以我研究了很多&到这个发布

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

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

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

之后我得到了 AwesomeCache 。它说这是一个很棒的API缓存。
但我不知道如何实现这个?
我参考了这个问题。我仍然无法理解。

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.

这是我的当前实现没有缓存的样子:

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)
         }

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

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

提前致谢!

更新

这些是我的要求


  1. 获取来自API& amp;的JSON解析JSON数据。这些可以在Alamofire& amp; SwiftyJSON

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

我将填充表视图中的已解析数据。它适用于用户在线时。

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

但我想在用户处于离线状态时显示表格中的数据。

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

所以我需要将Parsed数据或JSON数据保存在我的缓存和放大器中。我需要在一周或几天内刷新或过期缓存。

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.

请建议我实现这个目标的最佳途径...

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

推荐答案

您已经拥有许多工具。

您的所有请求都已存储在 NSURLCache NSURLSessionConfiguration 上的 NSURLSession 存储在< Alamofire的code> sharedInstance 经理。这些存储的请求已经遵循您正在服务的服务器提供的所有缓存策略规则。您可以通过在自己的自定义 requestCachePolicy 来控制缓存行为参考/ NSURLSessionConfiguration_class /> NSURLSessionConfiguration 。我还建议你阅读这篇非常棒的NSHipster文章,它将引导您了解 NSURLCache 的内容以及如何控制它。

All your requests are already stored in the NSURLCache in the NSURLSessionConfiguration on the NSURLSession stored inside the sharedInstance of 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 requestCachePolicy on your own custom NSURLSessionConfiguration. I'd also suggest you read through this awesome NSHipster article that walks you through the ins and outs of NSURLCache and how to control it.


创建自定义经理对象包含在当前的Alamofire中 docs

Creating custom Manager objects is covered in the current Alamofire docs.



正在下载JSON到磁盘



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

Downloading JSON to Disk

You can also download the JSON directly to disk using Alamofire.download instead of using Alamofire.request. This will download the payload to a fileURL that you provide in the destination closure. 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.

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

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


显然你没有有将JSON解析为模型对象,但这有助于保护你的表视图免受格式错误的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



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

Storing JSON for Offline Usage

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之类的内容中。您将使用Alamofire 请求方法与 responseJSON 序列化程序一起将数据解析为JSON。然后,您将JSON转换为模型对象。从那里,你将模型对象保存在CoreData中,然后最终使用模型对象填充表视图。

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 request method coupled with a responseJSON serializer 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.

这种方法的好处在于你拥有所有如果在设备脱机时访问表视图,则缓存模型对象。将此设计与查询耦合到 NSURLCache ,以查看您的请求是否已缓存,让您避免不必要的服务器调用,并在已生成模型对象时解析逻辑。

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 NSURLCache to see if your request is cached let's you avoid unnecessary server calls and parsing logic when you already have your model objects generated.


鉴于原始问题的更新,我建议采用这种方法。

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

这篇关于在SWIFT中从API缓存JSON的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆