[英]JSON fatal error: unexpectedly found nil while unwrapping an Optional value
I am not too sure why I am getting this error. 我不太确定为什么会收到此错误。 Is there something I am not checking for in terms of an optional value or some sort of option that I am missing
是否有我没有检查的可选值或我缺少的某种选项的东西
func getJSON(){
let url = NSURL(string: myURL)
let request = NSURLRequest(url: url! as URL)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request as URLRequest) { (data,response,error) -> Void in
if error == nil {
let swiftyJSON = JSON(data:data!)
let theTitle = swiftyJSON["results"].arrayValue
for title in theTitle{
let titles = title["title"].stringValue
print(titles)
}
} else{
print("Error")
}
}
task.resume()
}
If the error is that url
is nil when you force unwrap it, then that implies that on the line before it, where you create url
you've passed a value in myURL
that can't actually be parsed into an NSURL
object, for some reason. 如果错误是当您强行打开
url
时url
为nil,则意味着在它之前的那一行创建url
您已经在myURL
中传递了一个实际上无法解析为NSURL
对象的值,对于某些情况原因。
Print out myURL
and see what it is. 打印出
myURL
并查看它是什么。 I bet it isn't well-formed. 我敢打赌,它的格式不正确。
As an aside, you shouldn't be force unwrapping anyway. 顺便说一句,无论如何您都不应该强行打开包装。 Try something like this:
尝试这样的事情:
guard let url = NSURL(string: myURL) else {
print("Couldn't parse myURL = \(myURL)")
return
}
let request = NSURLRequest(url: url as URL) // <-- No need to force unwrap now.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.