Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

ios - NSString encoding returns nil on url content

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...