【发布时间】:2020-04-01 16:53:51
【问题描述】:
DispatchQueue.global().async{
do{
let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json")!
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let downloadedFriends = try decoder.decode([Friend].self, from: data)
DispatchQueue.main.async {
self.friends = downloadedFriends
self.tableView.reloadData()
}
}catch{
print(error.localizedDescription)
}
}
它打印:“数据无法读取,因为它丢失了。” 我检查了网址hackingwithswift,它是正确的
【问题讨论】:
-
不要使用
Data(contentsOf:)作为远程资源URL,使用正确的URLSession方法dataTask -
从不在解码
catch块中打印error.localizedDescription。打印error,它会准确告诉您哪里出了问题。
标签: swift networking swift5