Dair
Dair

Reputation: 16240

Why is retrieving the data from this URL returning nil?

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?

Upvotes: 0

Views: 1131

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

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

Upvotes: 2

Related Questions