Reputation: 759
I'm working with some API data that gets updated frequently.
I recently discovered that the data does not update properly on the phone, when it's updated on the server.
After hours on hours trying to troubleshoot this, I finally simply tried deleting the app from my phone, and reinstalling in. And it worked.
After some further testing I discovered that it's printing out old JSON.
Once I delete the app and reinstall it, it successfully prints out the correct updated JSON.
From that I gathered that it's probably an issue with the phone caching the old JSON data somehow.
So how can I go about clearing this cache in swift? or forcing it to make a new request.
(I'm using swiftyJson, although I don't think that has anything to do with this specific problem)
I did find one other question like this, but it's old (2014 in Obj-C) and there was no answers.
Here's how I get my data:
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
}
I tried changing my request to the following:
var request = init(formulaAPI: NSURL, cachePolicy: NSURLRequestCachePolicy, timeoutInterval: NSTimeInterval)
But that causes an error: "Use of local variable 'request' before it's declaration"
Any help figuring this out would be greatly appreciated!
Upvotes: 2
Views: 3018
Reputation: 104082
Instead of creating your request with,
NSURLRequest(URL: formulaAPI!)
you should use the following method so that you can explicitly set the cache policy.
var request = NSURLRequest(URL: formulaAPI!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 30)
NSURLRequest(URL:)
uses the default came policy, NSURLRequestUseProtocolCachePolicy
, and a time out interval of 60 seconds.
Upvotes: 11