NSString encoding returns nil on url content

2019-01-20 20:02发布

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条回答
我只想做你的唯一
2楼-- · 2019-01-20 20:44

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()
}
查看更多
登录 后发表回答