【问题标题】:Swift clearing JSON cache?快速清除 JSON 缓存?
【发布时间】:2015-08-12 14:19:55
【问题描述】:

我正在处理一些经常更新的 API 数据。

我最近发现数据在手机上没有正确更新,当它在服务器上更新时。

经过数小时尝试解决此问题,我终于尝试从手机中删除该应用程序,然后重新安装。它成功了。

经过进一步测试,我发现它正在打印出旧的 JSON。

删除应用并重新安装后,它会成功打印出正确更新的 JSON。

据我推测,这可能是手机以某种方式缓存旧 JSON 数据的问题。

那么我怎样才能快速清除这个缓存呢?或强制它提出新的请求。

(我正在使用 swiftyJson,虽然我认为这与这个特定问题没有任何关系)

我确实找到了另一个类似的问题,但它很旧(2014 年在 Obj-C 中)并且没有答案。

这是我获取数据的方式:

        var request = NSURLRequest(URL: formulaAPI!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        var formula = JSON(data: data!)

        // Loop through the api data.
        for (index: String, portfolio: JSON) in formula["portfolio"] {



            // Save the data into temporary variables
            tempStockName = portfolio["name"].stringValue
            tempTicker = portfolio["ticker"].stringValue
            tempPurchasePrice = portfolio["purchase_price"].floatValue.roundTo(2)
            tempWeight = portfolio["percentage_weight"].floatValue
            latestAPIPrice = portfolio["latest_price"].floatValue.roundTo(2)
            tempDaysHeld = portfolio["days_owned"].intValue

            // Continues on for quite a while, but the data in the above segment is definitely getting filled with old JSON data, so the issue is arising before this point
}

我尝试将我的请求更改为以下内容:

var request = init(formulaAPI: NSURL, cachePolicy: NSURLRequestCachePolicy, timeoutInterval: NSTimeInterval)

但这会导致错误:“在声明之前使用局部变量'request'”

任何解决此问题的帮助将不胜感激!

【问题讨论】:

  • 您应该显示您用于下载的代码。您是显式设置缓存策略,还是使用默认策略?
  • @rdelmar 添加了我的代码示例 :)
  • 真正使用requestWithURL:cachePolicy:timeoutInterval: 创建请求,并将NSURLRequestReloadIgnoringLocalCacheData 传递给cachePolicy 参数。
  • @rdelmar 感谢您的回复:)。我不在任何地方使用 requestWithURL,那么我将在哪里以及如何在我的请求中实现它?
  • 你确实使用了它,但在 Swift 语法中,var request = NSURLRequest(URL: formulaAPI!)。使用 init(URL theURL: NSURL, cachePolicy cachePolicy: NSURLRequestCachePolicy, timeoutInterval timeoutInterval: NSTimeInterval) 替换该行

标签: ios json swift caching


【解决方案1】:

而不是创建您的请求,

NSURLRequest(URL: formulaAPI!) 

您应该使用以下方法,以便您可以显式设置缓存策略。

var request = NSURLRequest(URL: formulaAPI!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 30)

NSURLRequest(URL:) 使用默认来电策略NSURLRequestUseProtocolCachePolicy,超时间隔为 60 秒。

【讨论】:

  • 你是个天才。非常感谢!
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 2019-06-19
  • 2011-07-25
相关资源
最近更新 更多