iosjsonswiftdatabasensurlsessiondatatask

iOS Swift - URLSessionDataTask doesn't get updated JSON data on refresh


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.


Solution

  • 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