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
1.2k views
in Technique[技术] by (71.8m points)

swift - NSData contentsOfURL constructor returns nil

I'm trying to access an API I made in PHP. It works fine in browser, but I can't get this code to fetch any sort of data from any given webpage.

var jsonData: NSData = NSData(contentsOfURL: NSURL(string: "http://www.google.com"))
let string1 = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
println(string1)

What am I doing wrong here?

Update: Here's the output after changing encoding.

enter image description here

Also, NSURLConnection doesn't start when I do that either. Might be a related issue.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

the code is correct but the data isn't in UTF it seems so it fails to make the NSString.

fails in swift & objC

for that server data is in NSISOLatin2StringEncoding

it differs based on the HTTP endpoint and normally UTF8 is fine


    var jsonData: NSData = NSData(contentsOfURL: NSURL(string: "https://www.google.com"))
    let string1 = NSString(data: jsonData, encoding: NSISOLatin1StringEncoding)
    println(string1)

shows the page's sourcecode


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

...