Yiming Chen Yiming Chen - 1 month ago 7
Swift Question

Why my return is nil but if i press the url in chrome/safari, i can get data?

@IBAction func mainButtonnBeTapped(sender: AnyObject) {
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: NSURL(string: "http://hq.sinajs.cn/list=sz000609")!)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let myString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("this is my string: \(myString)")
})
task.resume()
}


I am using above url to try to get some data, but the return is nil, but i enter the url in chrome/safari, i can get some data.
I really don't why, can anyone help to explain?

Answer

The text you try to get is probably not UTF-8, try with another encoding, like this for example:

let myString = NSString(data: data, encoding: NSASCIIStringEncoding)

Update: read Martin R's answer for how to find the right encoding.