我无法在swift中解码HTML页面中的数据

时间:2015-06-22 18:17:05

标签: html swift decode nsurlsession

我正在尝试将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)
})

2 个答案:

答案 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()