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)