Nick Balistreri Nick Balistreri - 25 days ago 9x
JSON Question

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

} else{


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)")

let request = NSURLRequest(url: url as URL)  // <-- No need to force unwrap now.