Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...