NSString encoding returns nil on url content

后端 未结 1 1297
你的背包
你的背包 2020-12-12 02:24

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 n

相关标签:
1条回答
  • 2020-12-12 02:53

    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()
    }
    
    0 讨论(0)
提交回复
热议问题