NSString编码在url内容上返回nil

我正在关注Udemy上的iOS Swift指南,这是我无法解决的第一个问题:

我应该看到HTML等打印到控制台,而是我得到空。

这是部分:

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

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

任何帮助? 解决之前,不能移动到下一个部分。

那里已经提到的问题是你正在使用的编码。 你需要使用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得到线索,你可以从响应中检测string编码:

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