0

I have a method which fetch data from JSON file on website. When I first lunch app it works just fine, but when data in JSON file are updated my method fetch still same data. I have to delete app app and install it again to get new data. here is my code:

private func fetchSchools(){
        let url = "https://www.example.com/inc/json.txt"
        let requestURL: NSURL = NSURL(string: url)!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
        let session = URLSession.shared
        session.dataTask(with: urlRequest as URLRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode


            if (statusCode == 200) {
                print("Everything is fine, file downloaded successfully.")

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : AnyObject]
                    if let JSONSchools = json?["skoly"] as? [[String : AnyObject]] {

                        for school in JSONSchools {

                            if let name = school["nazev"] as? String {

                                if let city = school["mesto"] as? String {

                                    if let id = school["id"] as? String {
                                        self.schools.append(School.init(name: name, city: city, id: id))
                                       // print(name)
                                    }

                                }

                            }
                        }
                        self.fetchFinished = true
                    }

                } catch {
                    print("Error with Json: \(error)")
                }
            }
        }

        .resume()
    }

I debugged my code and I realized that this: let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : AnyObject] fetch still the same data so it looks like JSONSerialization save the first fetch and then doesn't fetch from website but returns saved values.

Thanks for help

Edit: I changed my code to:

func fetchSchools(completion: @escaping (String) -> ()){
        let url = "https://www.example.com/inc/json.txt"
        let requestURL: NSURL = NSURL(string: url)!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
        let session = URLSession.shared
        session.dataTask(with: urlRequest as URLRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode


            if (statusCode == 200) {
                print("Everything is fine, file downloaded successfully.")

                if let data = data, let jsonString = String(data: data, encoding: String.Encoding.utf8), error == nil{
                    completion(jsonString)
                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
        }

        .resume()
    }

but it didn't changed my problem. Any ideas how to solve it?

Solution Finally I found this solution, my method was fine, but I fetch JSON from cache so I have to add this line of code to ignore the cache.

 var request = NSURLRequest(URL: requestURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 30)
Community
  • 1
  • 1
Ender
  • 13
  • 4
  • `session.dataTask` is asynchronous. You need to use a callback like in the linked example to properly extract the value from the closure each time you use it. – Eric Aya Apr 02 '17 at 10:46
  • thanks, but I am new in Swift programming so I have other question, does it mean that my fetching method is OK I just need to change appending to array to completion and in other method append to my array? – Ender Apr 02 '17 at 12:27
  • You need to replace `self.schools.append` with a callback, and in this callback you can append to the array (or do anything you want, like reloading a tableview after processing the new content, for example). The idea is: inside the .dataTask closure, as soon as you got workable content, use a callback to get the content out of the closure, *then* work with the content. :) – Eric Aya Apr 02 '17 at 12:29
  • Thanks a lot, I am going to try it – Ender Apr 02 '17 at 12:34
  • I changed my code but the results are still the same :-( – Ender Apr 02 '17 at 12:43
  • Look at my linked example, the "Swift 3 version". http://stackoverflow.com/a/31264556/2227743 Look how I call the method. Do the same, like: `fetchSchools() { (str) in print(str) }` but instead of print you parse your json and append to your array, then you update your UI. // BTW no need to make the JSON into a string... you should parse the json data itself like you did previously. – Eric Aya Apr 02 '17 at 12:51
  • In my reloadData function I print the data from fetch method and they are still the same as before – Ender Apr 02 '17 at 12:57
  • I can get the data that is not the problem the problem is that they are still same even the json file is changed – Ender Apr 02 '17 at 13:11
  • OK, thank you very much – Ender Apr 02 '17 at 13:17
  • Hi, I solved it, but I do not know what to do next when I have a string. How can I make from jsonString dictionary (or how I get data from the string)? I am sorry I have to ask you, but I don't know what to type to Gogle to find the solution – Ender Apr 03 '17 at 15:37
  • No problem - I'm glad you started to solve your issues, this is cool. As I mentioned in an earlier comment, you should not work with the JSON string in the first place. You don't have to. // Instead of getting a string out, get directly the data out. Then make an object from the data, with `JSONSerialization.jsonObject` and parse *this object*. Only look at the string version for debugging, not for real work. – Eric Aya Apr 03 '17 at 15:54
  • Have a look at these examples: http://stackoverflow.com/questions/35289389/downloading-json-with-nsurlsession-doesnt-return-any-data/35358750#35358750 – Eric Aya Apr 03 '17 at 15:57
  • http://stackoverflow.com/questions/36394565/swift-json-parsing-with-dictionary-with-array-of-dictionaries/36397593#36397593 – Eric Aya Apr 03 '17 at 15:57
  • http://stackoverflow.com/questions/36775068/results-wont-append-from-json/36775667#36775667 – Eric Aya Apr 03 '17 at 15:57
  • and finally: http://stackoverflow.com/questions/37340967/json-parsing-swift-array-has-no-value-outside-nsurlsession/37343547#37343547 :) – Eric Aya Apr 03 '17 at 15:58
  • Thank you very much – Ender Apr 03 '17 at 15:59

0 Answers0