Swift 清除 JSON 缓存?

Swift clearing JSON cache?

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

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

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

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

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

据我所知,这可能是 phone 以某种方式缓存旧 JSON 数据的问题。

那么我该如何清除 swift 中的这个缓存呢?或者强制它提出新的请求。

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

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

这是我获取数据的方式:

        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)

但这会导致错误:"Use of local variable 'request' before it's declaration"

如果能帮助解决这个问题,我们将不胜感激!

而不是创建您的请求,

NSURLRequest(URL: formulaAPI!) 

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

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

NSURLRequest(URL:) 使用默认的策略 NSURLRequestUseProtocolCachePolicy 和 60 秒的超时间隔。