将JSON数据保存在设备的缓存中

时间:2015-04-27 07:25:33

标签: ios json swift caching

我想保存从手机缓存中的URL获取的JSON数据。为此我做了:

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

        // Create a custom configuration
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        var defaultHeaders = 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 = Manager(configuration: configuration)

        // Make your request with your custom manager that is caching your requests by default
        manager.request(.GET, "http://some_site.az/ru/json-view/1",  encoding: .URL)
            .response { (request, response, data, error) in
                var myJ = NSJSONSerialization.JSONObjectWithData(data as! NSData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

                var dataForPrint = JSON(myJ)

                var infoTitle = dataForPrint["result"][0]["title"]
                var infoBody = dataForPrint["result"][0]["body"]

                self.aboutUs.loadHTMLString(infoBody.stringValue, baseURL: nil)

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

但它根本不会缓存它。我做错了什么?

更新

我确实说过,我确实关注过这个问题,对其进行了修改并且无效!

0 个答案:

没有答案