【发布时间】:2018-09-30 22:49:34
【问题描述】:
我是 Swift 编程的新手,当数据可用时,我为我的项目使用了 Api,它运行良好,如果数据不可用,应用程序在 JSONSerialization 中崩溃,问题出在 data?.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 != nil而不是if data?.count != 0 -
使用
if let或guard let而不是检查 nil 或 count -
if let or guard let ...什么意思
-
这意味着如果数据有值,那么它会创建一个属性,即:
if let temp = data意味着如果数据不是 nil 你有 temp else 跳过 if 中的代码 -
ya....我明白了,谢谢 Tj3n
标签: ios swift api web-services swift3