我有一个从网站上的JSON文件中获取数据的方法。当我第一次午餐app它工作得很好,但是当JSON文件中的数据更新时,我的方法仍然获取相同的数据。我必须删除app app并再次安装才能获得新数据。这是我的代码:
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()
}
我调试了我的代码,我意识到这一点:let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : AnyObject]
获取仍然相同的数据,因此它看起来像JSONSerialization保存第一次获取,然后不从网站获取但返回保存的值。
感谢您的帮助
修改:我将代码更改为:
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()
}
但它没有改变我的问题。 任何想法如何解决?
解决方案 最后我发现this solution,我的方法很好,但我从缓存中获取JSON,所以我必须添加这行代码来忽略缓存。
var request = NSURLRequest(URL: requestURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 30)