我正在使用Swift从Coronavirus API获取JSON。但是,当我尝试运行代码时,出现此错误。
致命错误:展开一个可选值时意外发现nil:第22行
我的代码部分是
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22}"
getData(from: url)
// Do any additional setup after loading the view.
}
private func getData(from url: String) {
let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
guard let data = data, error == nil else{
print("Something Went Wrong")
return
}
//Have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch{
print("failed to convert \(error.localizedDescription)")
}
guard let json = result else {
return
}
print(json.data.date)
})
getfromurl.resume()
}
第22行是:
let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
我很困惑,因为我认为这意味着url
没有分配任何东西,但是即使调试器也认为确实如此。
更新:
我可以获取数据,但是一旦获取错误。错误是:
无法转换valueNotFound(Swift.Int,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ data”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),CodingKeys(stringValue:“ newDeathsByDeathDate“,intValue:nil)],debugDescription:” Expert Int值,但发现为null。“,底层错误:nil))
转换失败表明解码JSON和值时出错。
唯一的例外并不是说url
是nil
,但是URL(string:url)
是nil
您需要检查url
字符串是否是有效的网址:
private func getData(from url: String) {
guard let theURL = URL(string: url) else { print ("oops"); return }
let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
/* ... */
}
}
由于现在给出了url字符串:问题是花括号;在RFC1738中将它们标记为不安全,应将其替换为(打开)和(关闭),因此:%7b
%7d
let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d"
let theUrl = URL(string: url)
print (theUrl)
这也是官方API文档中的示例:
curl -si 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7B%22name%22:%22areaName%22%7D'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句