我正在使用URLSession从我的网站抓取JSON数据。我的代码抛出与转换类型有关的各种错误,因此我在代码中添加了一些打印语句,并发现此功能出于某种原因正在访问我的网站的较早版本。此后,我已经更新了网站的数据,并通过自己访问网站和使用Rested验证了新数据是否正确显示。但是,下面代码中的打印语句会产生旧数据。该代码不会从磁盘读取数据,因此我不确定为什么会发生这种情况。
出于隐私目的,我已经从代码中删除了网站的链接,但可以在下面找到该功能。
func websiteToDisk() {
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
let defaultSession = URLSession(configuration: config)
let url = URL(string: someURL)
let task = defaultSession.dataTask(with: url!) { data, response, error in
do {
print("Getting information from website")
if let error = error {
print(error.localizedDescription)
} else if let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
//do {
let jsonDecoder = JSONDecoder()
print("about to dcode")
let decodedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]//try jsonDecoder.decode([String: [String]].self, from: data)
print(decodedData)
print("accessing dictionary")
print(decodedData!["busLoops"])
let toWrite = decodedData!["busLoops"] as! [String]
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let busLoopsURL = documentDirectoryURL.appendingPathComponent("busLoops").appendingPathExtension("json")
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(toWrite)
try jsonData.write(to: busLoopsURL)
//} catch { print(error)}
}
}
catch { print(error)}
}
task.resume()
}
答案 0 :(得分:1)
尝试忽略本地缓存数据
guard let url = URL(string: "http://....") else{
return
}
let request = NSMutableURLRequest(url: url)
request.cachePolicy = .reloadIgnoringCacheData
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, resp, error) in
}
task.resume()