NSString编码在网址内容

时间:2016-01-08 23:22:09

标签: ios swift nsstring nsurl

我正在关注Udemy的iOS Swift指南,这是我无法解决的第一个问题:

我应该看到html等打印到控制台,但我得到了null。

这是一节:

    let url = NSURL(string: "https://google.com")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
        (data, response, error) in
        if error == nil {
            var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(urlContent)
        }
    } 
    task.resume()

如果我只打印数据,那么它会给我一些内容,但是当它编码为零时。

有任何帮助吗?在解决之前无法进入下一部分。

1 个答案:

答案 0 :(得分:1)

rmaddy已经提到的问题是你正在使用的编码。您需要使用NSASCIIStringEncoding

if let url = URL(string: "https://www.google.com") {
    URLSession.shared.dataTask(with: url) {
        data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let data = data, error == nil,
            let urlContent = String(data: data, encoding: .ascii)
        else { return }
        print(urlContent)
    }.resume()
}

或者从Martin R中获取线索,您可以从响应中检测字符串编码:

extension String {
    var textEncodingToStringEncoding: Encoding {
        return Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(self as CFString)))
    }
}
if let url = URL(string: "https://www.google.com") {
    URLSession.shared.dataTask(with: url) {
        data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let data = data, error == nil,
            let textEncoding = response?.textEncodingName,
            let urlContent = String(data: data, encoding: textEncoding.textEncodingToStringEncoding)
            else { return }
        print(urlContent)
    }.resume()
}