1

I have a simple app where I get data from a JSON file stored in my own server in this way - I'm using SwiftyJSON:

func queryData(_ fileName:String) {
        guard let url = URL(string: JSON_PATH + fileName + ".json") else {return} // JSON_PATH + fileName + ".json" is the complete path to my db.json file (see below)
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let dataResponse = data, error == nil else {
                self.simpleAlert(error!.localizedDescription)
                return
            }
            let jsonData = try! JSON(data: dataResponse)
            print("ARRAY: \(jsonData)")
        }
        task.resume()
    }



Here's my db.json file:

[
    {
        "objID":"GNoW3vszYz",
        "string":"First (1) string",
        "pointer":["pointer","yN76TF43i8"],
        "boolean":true,
        "number":123,
        "fileURL":"https://example.com/uploads/01.jpg",
        "array":["aaa","bbb","ccc"]
    },
    {
        "objID":"yN76TF43lD",
        "string":"Second (2) string",
        "pointer":["pointer","GNoN3vsz2I"],
        "boolean":false,
        "number":12.55,
        "fileURL":"https://example.com/uploads/02.jpg",
        "array":["aaa","eee","fff"]
    }
]



The problem is that if I manually edit my db.json file, let's say I change "number":123, into "number":5555, save and upload it again in my server and run my app again, the console log shows me the same JSON data as above, like if I had changed nothing.


I've tried to kill the app and run it again 2-3 times with Xcode, no success, the only way I can get the updated JSON file data is to delete the app and install it again via Xcode.

Is there a way to always get updated JSON data with URLSessionDataTask?
Thanks.

Frank Eno
  • 2,581
  • 2
  • 31
  • 54
  • If your server has "Cache-Control" enabled URLSession will cache data.Create URLSessionConfiguration and set its requestCachePolicy to reloadIgnoringLocalCacheData.To check this print response and check the value of "Cache-Control" – Vikky Jul 31 '19 at 08:11

3 Answers3

6

This is due to URLSession caching the data from the server, this is usually sent in the header of the json file coming from the server.

If you can't change anything on the server side then on you can just use the .ephemeral which apple documents here

use this code

let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: configuration)

.ephemeral is used for data that will only be stored in ram and nothing will be stored on disk

F22lightning
  • 620
  • 6
  • 16
4

I can think of two ways.

1) add current date time at the end of your url

2) Disable Local Cache.

For 1)

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

let url = URL(string: JSON_PATH + fileName + ".json?q=\(Date().currentTimeMillis())")

For 2)

let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil

let session = URLSession.init(configuration: config)

Taken From this SO

Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
1

This behavior also can happen with text files (and other non-JSON files) stored on a web server and by using URLSession to fetch data from that text file. .ephemeral also works in this case.

if let url = URL(string: "http://www.somerandomsite.com/mydata.txt") {
     let configuration = URLSessionConfiguration.ephemeral
     var urlSession = URLSession(configuration: configuration).dataTask(with: url) {(data, response, error) in
           if let error = error {
                print(error)
           }
      if var textFile = String(data: data!, encoding: .utf8){
           print(textFile)
      }
}
urlSession.resume()
Will Buffington
  • 1,048
  • 11
  • 13