【问题标题】:NSJSONSerialization not updating (possibly getting cached)NSJSONSerialization 未更新(可能被缓存)
【发布时间】:2014-12-04 00:08:40
【问题描述】:

您好,我正在使用 NSJSONSerialization 将我的应用程序中的 JSON 下载到设备,似乎当我更新 JSON 文件并重新运行下载 JSON 函数时,它不会下载新的 JSON。它只是下载未更新的 JSON 文件。我尝试在不同的设备上运行该应用程序,它第一次运行,但是一旦我再次更新 JSON,它就不会下载新的 JSON。我在想它可能会被缓存,但我不确定。

这是我的代码:

func downloadJSON(){

    let p =  NSURLRequest(URL: NSURL(string: "https://themartini.co/pythonStuff/quotey.json")!)

    let sharedSession = NSURLSession.sharedSession()

    let dwn = sharedSession.dataTaskWithRequest(p, completionHandler: { (data : NSData!,re : NSURLResponse!, error: NSError!) -> Void in

        if error == nil {

            let js : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSArray // downloads JSON and puuts it into an array

            println(js)



            dispatch_async(dispatch_get_main_queue()){

                self.quotes = js as NSArray

                NSNotificationCenter.defaultCenter().postNotificationName("dataTaskFinished", object: nil)

            }

        }

    })

    dwn.resume()

}

有什么想法吗?谢谢。

【问题讨论】:

  • ...您已经消除了中间 CDN 作为原因?您从设备切换到设备的速度有多快?真正的解决办法是让您的服务器提供正确的缓存策略。

标签: ios iphone json swift


【解决方案1】:

您应该将正确的缓存策略传递给您的NSURLRequest。有一个包含此参数的alternative constructor

let p = NSURLRequest(URL: url, 
                     cachePolicy: ReloadIgnoringLocalCacheData,
                     timeoutInterval: 15.0)

【讨论】:

  • NSURLSession 和 NSURLConnection 等同于上述任务。
【解决方案2】:

你可以在你的 NSURLRequest 中添加一个 cachebuster。 (把网址改成https://themartini.co/pythonStuff/quotey.json?23421231231

最后的数字串是随机的。这将破坏缓存。另外,不要使用 NSURLSession,而是查看 NSURLConnection.SendAsynchroniousRequest

【讨论】:

  • 每次调用 JSON 下载函数时,我会在 iOS 端更改 URL 末尾的数字吗?谢谢。
  • 是的。这就是想法。缓存依赖 URL 来返回相同的数据。另外,嘿,Yismo。
  • @Moshe 所以我基本上会随机生成数字并将其添加到 URL 中?另外,你好!
  • @Moshe & Michael Voznesensky 为什么比 NSURLSesion 更好?
  • @Moshe 对其他答案有什么想法吗?
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 2020-10-27
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2017-02-23
相关资源
最近更新 更多