0

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

1 Answers1

2

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.
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • wow thank you so much. So is unwrapping like a safety net of sorts? – Nick Balistreri Sep 29 '16 at 16:59
  • 1
    Not exactly. There are some cases where you need to say, "no, really, trust me, I know what I'm doing", but for the most part if you have an optional, you need to properly unwrap it before using it. The easiest way is to use `guard let foo = someOptional` or `if let foo = someOptional`. – i_am_jorf Sep 29 '16 at 17:01
  • Much appreciated. I am new to swift so this was very helpful – Nick Balistreri Sep 29 '16 at 17:03
  • Further reading: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html – i_am_jorf Sep 29 '16 at 17:06
  • 1
    @NickBalistreri You should see http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu and read the relevant sections of Apple's "The Swift Programming Language" book. – rmaddy Sep 29 '16 at 17:07