Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...