@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()
}
我正在使用上面的url尝试获取一些数据,但返回值为nil,但我输入chrome / safari中的url,我可以得到一些数据。 我真的不知道为什么,任何人都可以帮忙解释一下吗?
答案 0 :(得分:9)
此HTTP服务器发送
Content-Type = application/x-javascript; charset=GBK
响应中的标头字段,因此您可以从textEncodingName
的{{1}}属性获得正确的编码。这可以
转换为NSURLResponse
。
这只是https://stackoverflow.com/a/19885463/1187415向Swift提供的解决方案的翻译,加上一些 简单的错误检查:
NSStringEncoding
输出:
this is my string: var hq_str_sz000609="绵世股份, ....
Swift 2:
需要进行细微更改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
var usedEncoding = NSUTF8StringEncoding // Some fallback value
if let encodingName = response.textEncodingName {
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
if encoding != UInt(kCFStringEncodingInvalidId) {
usedEncoding = encoding
}
}
if let myString = NSString(data: data, encoding: usedEncoding) {
println("this is my string: \(myString)")
} else {
println("failed to decode data")
}
})
task.resume()
更新 Swift 3:
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
var usedEncoding = NSUTF8StringEncoding // Some fallback value
if let encodingName = response?.textEncodingName {
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
if encoding != UInt(kCFStringEncodingInvalidId) {
usedEncoding = encoding
}
}
if let myString = String(data: data!, encoding: usedEncoding) {
print("this is my string: \(myString)")
} else {
print("failed to decode data")
}
})
task.resume()
答案 1 :(得分:2)
您尝试获取的文本可能不是UTF-8,请尝试使用其他编码,例如:
let myString = NSString(data: data, encoding: NSASCIIStringEncoding)
更新:阅读Martin R有关如何找到正确编码的答案。