0

I am following this post for getting JSON data and for some reason this function:

func getJSON(urlToRequest: String) -> NSData {
    return NSData(contentsOfURL: NSURL(string: urlToRequest)!)!
}

returns nil as I get the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have broken up the function:

func getJSON(urlToRequest: String) -> NSData {
    let url : NSURL! = NSURL(string: urlToRequest)
    let data : NSData! = NSData(contentsOfURL: url)
    return data
}

And according to my debugger:

Printing description of url:
www.reddit.com/r/earthporn/.json
Printing description of data:
(NSData!) data = nil

Pasting in the URL to Chrome doesn't give a blank page. It gives a massive glob of JSON, so I am confused why data is nil?

Community
  • 1
  • 1
Dair
  • 15,910
  • 9
  • 62
  • 107
  • Use the version of the function which returns you error information – Wain Apr 05 '15 at 07:24
  • www.reddit.com/r/earthporn/.json - I wouldn't expect any data from the URL. And you have written your code to crash if there is no data. – gnasher729 Apr 05 '15 at 07:27
  • You forgot to add the url scheme. try using "h t t p://www.reddit.com/r/earthporn/.json" – Leo Dabus Apr 05 '15 at 07:28
  • Thanks everyone for the help, the major issue was the url scheme, I thought it was implicit. My bad. – Dair Apr 05 '15 at 07:36

1 Answers1

2

You forgot to add the url scheme. NSURL needs the full address. You should also use if let to safely unwrap your optional data:

func getJSON(urlToRequest: String) -> NSData? {
    if let url = NSURL(string: urlToRequest) {
        if let data = NSData(contentsOfURL: url) {
            return data
        }
    }
    return nil
}

if let myData = getJSON("http://www.reddit.com/r/earthporn/.json") {
    println("there is data")   // "there is data in myData"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571