NSString encoding returns nil on url content

 ̄綄美尐妖づ 提交于 2019-12-18 09:35:04

问题


I'm following an iOS Swift guide on Udemy and this is the first issue I cannot work around:

I am supposed to see html etc printed to the console but instead I get null.

This is the section:

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

If I print just the data then it gives me some content back but when its encoded its nil.

Any help? Cannot move onto the next part until this is resolved.


回答1:


The problem there as already mentioned by rmaddy it is the encoding you are using. You need to use 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()
}

Or taking a clue from Martin R you can detect the string encoding from the response:

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()
}


来源:https://stackoverflow.com/questions/34687730/nsstring-encoding-returns-nil-on-url-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!