【发布时间】:2018-08-27 01:22:35
【问题描述】:
我正在使用 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()
}
【问题讨论】:
-
那么你的问题是什么?
-
如何推断
-
“如何推断”?这意味着什么?推断什么,从什么?具体点,伙计!
标签: ios swift nsurlsession