2

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.

Anton O.
  • 653
  • 7
  • 27
Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • 1
    If `data` isn't `nil` but `urlContent` is, then this means that the data doesn't represent a UTF-8 encoded string. It may be in another encoding or it isn't string data. – rmaddy Jan 08 '16 at 23:25
  • 1
    This might be useful: http://stackoverflow.com/a/32051684/1187415, it is a method to *detect* the encoding from the HTTP response header. If that does not work, try NSWindowsCP1252StringEncoding or NSISOLatin1StringEncoding. – Martin R Jan 08 '16 at 23:54

1 Answers1

2

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()
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571