在iOS Swift中将远程JSON数据同步到本地缓存存储 [英] Synchronizing remote JSON data to local cache storage in iOS Swift

查看:163
本文介绍了在iOS Swift中将远程JSON数据同步到本地缓存存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到解决方案,以简单处理iOS设备上只读消耗远程JSON数据的所有必要步骤。这意味着获取远程JSON数据,存储到iOS设备上的本地缓存以供脱机使用,刷新缓存,解析JSON数据。我认为现在所有移动应用都是非常普遍的要求。

I am trying to find the solution for simple processing all necessary steps for read-only consuming remote JSON data on iOS devices. It means fetching remote JSON data, store to local cache on iOS device for offline usage, refresh the cache, parsing JSON data. I think it is very common requirement for all mobile apps nowadays.

我知道可以手动下载远程JSON文件,将其存储到本地数据库或iOS设备上的文件当网络不可用时从本地存储中获取它,否则从网络下载它。我现在手动完成。 :)但是很多步骤希望可以通过使用框架/库来实现,不是吗?

I know it is possible to manually download remote JSON file, store it to local db or file on iOS device and when network is not available fetch it from local storage otherwise dowload it from net. I do it manually now. :) But it is lot of steps which hope is possible to do by using frameworks/libraries, isn't?

所以我尝试了几乎所有我做的所有事情的HanekeSwift框架需要,但它只缓存远程JSON(和图像),但不刷新缓存!这对我没用。我也知道存在Alamofire和SwiftyJSON,但我对它们没有任何经验。

So I tried HanekeSwift framework which do almost everything what I need but it only do caching remote JSON (and Images) but doesn't refresh the cache!! which is not useful for me. I know also that exists Alamofire and SwiftyJSON but I don't have any experience with them.

你有什么经验怎么做?

摘要


  • Swift中支持iOS8的库或框架

  • 下载远程JSON并存储到本地缓存

  • 从其原点刷新本地缓存的可能性

  • 很好的奖金很容易JSON解析

  • libraries or frameworks for iOS8 support in Swift
  • download remote JSON and store to local cache
  • possibility to refresh local cache from it's origin
  • nice bonus is easy JSON parsing

谢谢! Michal

Thank you! Michal

推荐答案

很棒的问题!

你绝对可以用Alamofire和SwiftyJSON的组合。我建议的是将几件事情结合起来尽可能简单。

You can absolutely accomplish this with a combination of Alamofire and SwiftyJSON. What I would recommend is a combination of several things to make this as easy as possible.

我认为你有两种获取JSON的方法。

I think you have two approaches to fetching the JSON.


  1. 在内存中获取JSON数据并使用缓存策略

  2. 将JSON数据直接下载到本地缓存

选项1

// Create a shared URL cache
let memoryCapacity = 500 * 1024 * 1024; // 500 MB
let diskCapacity = 500 * 1024 * 1024; // 500 MB
let cache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")

// Create a custom configuration
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders
configuration.HTTPAdditionalHeaders = defaultHeaders
configuration.requestCachePolicy = .UseProtocolCachePolicy // this is the default
configuration.URLCache = cache

// Create your own manager instance that uses your custom configuration
let manager = Alamofire.Manager(configuration: configuration)

// Make your request with your custom manager that is caching your requests by default
manager.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"], encoding: .URL)
       .response { (request, response, data, error) in
           println(request)
           println(response)
           println(error)

           // Now parse the data using SwiftyJSON
           // This will come from your custom cache if it is not expired,
           // and from the network if it is expired
       }

选项2

let URL = NSURL(string: "/whereever/your/local/cache/lives")!

let downloadRequest = Alamofire.download(.GET, "http://httpbin.org/get") { (_, _) -> NSURL in
    return URL
}

downloadRequest.response { request, response, _, error in
    // Read data into memory from local cache file now in URL
}

选项1 肯定会利用最大数量的Apple支持缓存。我想你正在尝试做什么,你应该能够利用 NSURLSessionConfiguration 和一个特定的缓存策略,以实现您的目标。

Option 1 certainly leverages the largest amount of Apple supported caching. I think with what you're trying to do, you should be able to leverage the NSURLSessionConfiguration and a particular cache policy to accomplish what you're looking to do.

选项2 需要更多的工作量,如果您利用实际缓存磁盘上数据的缓存策略,将会是一个奇怪的系统。下载最终将复制已缓存的数据。以下是您的自定义网址缓存中存在请求时的流程。

Option 2 will require a much larger amount of work, and will be a bit of a strange system if you leverage a cache policy that actually caches data on disk. Downloads would end up copying already cached data. Here's what the flow would be like if your request existed in your custom url cache.


  1. 提供下载请求

  2. 请求被缓存,因此加载到NSInputStream中的缓存数据

  3. 数据通过NSOutputStream
  4. $写入提供的 URL b $ b
  5. 调用响应序列化程序将数据重新加载到内存中

  6. 然后使用SwiftyJSON将数据解析为模型对象

  1. Make download request
  2. Request is cached so cached data loaded into NSInputStream
  3. Data is written to the provided URL through NSOutputStream
  4. Response serializer is called where you load the data back into memory
  5. Data is then parsed using SwiftyJSON into model objects

除非你下载非常大的文件,否则这很浪费。如果将所有请求数据加载到内存中,则可能会遇到内存问题。

This is quite wasteful unless you are downloading very large files. You could potentially run into memory issues if you load all the request data into memory.


将缓存的数据复制到提供的 URL 很可能通过NSInputStream和NSOutputStream实现。这一切都由Apple在Foundation框架内部处理。这应该是一种非常有效的内存移动数据的方法。缺点是您需要复制整个数据集才能访问它。

Copying the cached data to the provided URL will most likely be implemented through NSInputStream and NSOutputStream. This is all handled internally by Apple by the Foundation framework. This should be a very memory efficient way to move the data. The downside is that you need to copy the entire dataset before you can access it.

NSURLCache

这里可能非常有用的另一件事是能够直接从 NSURLCache 获取缓存响应。看一下可以找到的 cachedReponseForRequest:方法 here

One other thing that may be very useful here for you is the ability to fetch a cached response directly from your NSURLCache. Take a look at the cachedReponseForRequest: method which can be found here.

SwiftyJSON

最后一步是将JSON数据解析为模型对象。 SwiftyJSON让这很容易。如果您使用上面的选项1 ,则可以使用 Alamofire-SwiftyJSON中的自定义响应序列化程序。这看起来如下所示:

The last step is parsing the JSON data into model objects. SwiftyJSON makes this very easy. If you're using Option 1 from above, then you could use the custom response serializer in the Alamofire-SwiftyJSON. That would look something like the following:

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .responseSwiftyJSON { (request, response, json, error) in
             println(json)
             println(error)
         }

现在,如果您使用选项2 ,则需要加载来自磁盘的数据,然后初始化SwiftyJSON对象并开始解析,看起来像这样:

Now if you used Option 2, you'll need to load the data from disk, then initialize a SwiftyJSON object and begin parsing which would look something like this:

let data = NSData(contentsOfFile: URL.path)!
let json = JSON(data: data)

这应涵盖其中的所有工具你需要完成你的尝试。你如何构建精确的解决方案当然取决于你,因为有很多可能的方法来做到这一点。

That should cover all the tools in that you should need to accomplish what you attempting. How you architect the exact solution is certainly up to you since there are so many possible ways to do it.

这篇关于在iOS Swift中将远程JSON数据同步到本地缓存存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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