0

This is my first app and I'm wondering if I have made a mistake with regards to using URLSession.shared dataTask because I am not seeing my app get new data which is frequently updated. I see the new json instantly in my browser when I refresh, but, my app apparently does not see it.

Will it ever get the new json data from my server without uninstalling the app?

There are some some similar question topics, such as How to disable caching from NSURLSessionTask however, I do not want to disable all caching. Instead, I want to know how this default object behaves in this scenario - How long is it going to cache it? If indeed the answer is forever, or until they update or reinstall the app, then I will want to know how to reproduce the normal browser based cache behavior, using if-modified-since header, but that is not my question here.

I call my download() function below gratuitously after the launch sequence.

func download(_ ch: @escaping (_ data: Data?, _ respone: URLResponse?, _ error: Error?) -> (), completionHandler: @escaping (_ sessionError: Error?) -> ()) {

    let myFileURL: URL? = getFileURL(filename: self.getFilename(self.jsonTestName))

    let myTestURL = URL(string:getURLString(jsonTestName))
    let session = URLSession.shared

    // now we call dataTask and we see a CH and it calls My CH

    let task = session.dataTask(with: myTestURL!) { (data, response, error) // generic CH for dataTask
        in

        // my special CH
        ch(data,response,error)  // make sure the file gets written in this ch
    }
    task.resume()  // no such thing as status in async here
}

Within the completion handler which I pass to download, I save the data with this code from "ch":

                DispatchQueue.main.async {

                    let documentController = UIDocumentInteractionController.init(url: myFileURL!)
                    documentController.delegate = self as UIDocumentInteractionControllerDelegate

                }

and then finally, I read the data within that same completion handler from disk as such:

 let data = try Data(contentsOf: myFileURL!)

For clarification, my complete calling function from which I call download() with completion handler code.

  func get_test(){ // download new tests
    let t = testOrganizer
    let myFileURL: URL? = t.getFileURL(filename:t.getFilename(t.jsonTestName))

    t.download( { (data,response,error)
        in
        var status: Int! = 0
        status = (response as? HTTPURLResponse)?.statusCode
        if(status == nil) {
            status = 0
        }
        if(error != nil || (status != 200 && status != 304)) {

            let alertController = UIAlertController(title: "Error downloading", message:"Could not download updated test data.  HTTP Status: \(status!)", preferredStyle: UIAlertControllerStyle.alert)
            alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil))
            self.present(alertController, animated: true, completion: nil)
            self.p.print("END OF COMPLETION HANDLER")
        }
        else {
            let status = (response as! HTTPURLResponse).statusCode

            print("Success: status = ", status)

            self.p.print("WRITING FILE IN COMPLETION HANDLER")

            do {
                try data!.write(to: myFileURL!)

                DispatchQueue.main.async {

                    let documentController = UIDocumentInteractionController.init(url: myFileURL!)
                    documentController.delegate = self as UIDocumentInteractionControllerDelegate

                }

            } catch {
               // // _ = completionHandler(NSError(domain:"Write failed", code:190, userInfo:nil))
                print("error writing file \(myFileURL!) : \(error)")
            }

            self.myJson = self.testOrganizer.readJson()

            self.p.print("END OF COMPLETION HANDLER")

        }
        }, completionHandler: {
        sessionError in
        if(sessionError == nil) {
            print("Downloaded and saved file successfully")
        } else {
            let alertController = UIAlertController(title: "get_tests", message:
                "Failed to download new tests - " + sessionError.debugDescription, preferredStyle: UIAlertControllerStyle.alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
            self.present(alertController, animated: true, completion: nil)
        }
    }) 
}

0 Answers0