JSON fatal error: unexpectedly found nil while unwrapping an Optional value

JSON fatal error: unexpectedly found nil while unwrapping an Optional value

我不太清楚为什么会收到此错误。是否有我没有检查的可选值或我缺少的某种选项

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()
}

如果错误是 url 在你强制展开它时为 nil,那么这意味着在它之前的那一行,你创建 url 的地方你已经在 [= 中传递了一个值13=] 由于某种原因,实际上无法解析为 NSURL 对象。

打印出来myURL看看是什么。我敢打赌它的格式不正确。

顺便说一句,无论如何你都不应该强行展开。尝试这样的事情:

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.