我正在尝试将HTML页面中的数据解码为可读,但urlContent
字符串为零,即使从data
返回的NSURlSession
为非零。
我的实施:
var city = "London"
var url = NSURL(string: "https://www.google.com/#safe=off&q=weather+in+" + city.stringByReplacingOccurrencesOfString(" ", withString: "+"))
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data , response, error) -> Void in
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
println(urlContent)
})
答案 0 :(得分:1)
data
是可选的NSData
(或“NSData?
”)。你必须打开它。
更新:我转发到NSASCIIStringEncoding
(来自NSUTF8StringEncoding
),正如Eric D.指出的那样。我还更新了Swift 2的代码。
这对我有用:
let city = "London"
let url = NSURL(string: "https://www.google.com/#safe=off&q=weather+in+" + city.stringByReplacingOccurrencesOfString(" ", withString: "+"))
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data , response, error) -> Void in
if let data = data,
urlContent = NSString(data: data, encoding: NSASCIIStringEncoding) {
print(urlContent)
} else {
print("Error: \(error)")
}
})
task.resume()
答案 1 :(得分:1)
Aaron Brager的答案通常会起作用,但在此特定情况下,由于编码服务器端,您必须使用NSASCIIStringEncoding
代替NSUTF8StringEncoding
解码HTML
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data , response, error) -> Void in
if let data = data {
var urlContent = NSString(data: data, encoding: NSASCIIStringEncoding)
println(urlContent)
} else {
println("Error: \(error)")
}
})
task.resume()