我是 Swift 编程的新手,当数据可用时,我已经为我的项目使用了 Api,它工作完美,如果数据不可用,应用程序在 JSONSerialization 中崩溃,问题出在数据中?.count != 0,因为 data.count 主要是 2 或其他一些数字,如果我尝试更改导致错误的那条线。我不知道如何解决这个问题,任何人都可以建议我。
func getData() {
guard let URL = Foundation.URL(string:"http://xxxxx/xxx?xx=\(userid)") else {
return
}
let request = URLRequest(url: URL)
let task = URLSession.shared.dataTask(with: request, completionHandler: { data,response,error in
guard error == nil && data != nil else {
let alert = UIAlertController(title: "Check your Internet Connection", message: "", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
return
}
print(data?.count)
if data?.count != 0 {
let received = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) //Here getting thread error
print(received)
})
task.resume()
}
}
最佳答案
问题出在这部分。
if data?.count != 0
{
let received = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) //Here getting thread error
print(received)
}
所以使用 if let 或 guard 重写它。
guard let responseData = data else{
return
}
现在您可以在 JSONSerialization 方法中使用 responseData。所以整个代码片段看起来像
guard let responseData = data else{
return
}
let received = try! JSONSerialization.jsonObject(with: responseData, options:.allowFragments)
print(received)
在 Swift 中,如果 let 和 guard 用于展开可选值。使用 ”!”如果展开的值为 nil,则展开可选将导致崩溃。我们使用 if let 或 guard 来安全地解包可选值。所以作为经验法则,你应该只使用“!”当您 101% 确定它不会包含 nil 值时,打开可选值。
关于ios - 应用程序使用 swift 使用 API 时会崩溃吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937915/