Nick Balistreri
Nick Balistreri

Reputation: 131

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

Upvotes: 0

Views: 946

Answers (1)

i_am_jorf
i_am_jorf

Reputation: 54600

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.

Print out myURL and see what it is. 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.

Upvotes: 2

Related Questions