小编典典

NSString编码在URL内容上返回nil

swift

我正在关注有关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()

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

有什么帮助吗?在解决此问题之前,无法移动到下一部分。


阅读 250

收藏
2020-07-07

共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()
}
2020-07-07