1

I am trying to get and print the HTML from a URL. Here's how I do it (with Swift 2):

let testUrl = NSURL(string: "https://www.google.com")
var html = NSString()
do {
    html = try NSString(contentsOfURL: testUrl!, encoding: NSUTF8StringEncoding)
} catch{print(error)}
print(html)

And the following error is printed in console:

Error Domain=NSCocoaErrorDomain Code=261 "The file couldn’t be opened using text encoding Unicode (UTF-8)." UserInfo={NSURL=https://www.google.com, NSStringEncoding=4}

Any idea?

hklel
  • 1,624
  • 23
  • 45

3 Answers3

7

It seems that www.google.com sends the response using the ISO 8859-1 encoding, the corresponding NSString encoding is NSISOLatin1StringEncoding:

html = try NSString(contentsOfURL: testUrl!, encoding: NSISOLatin1StringEncoding)

You can also detect the HTTP response encoding automatically, see for example https://stackoverflow.com/a/32051684/1187415.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks for your answer, it works but when I tried another url like https://www.google.com/search?q=%20site:%20stackoverflow.com I got an error saying that The file “search” couldn’t be opened. I've tried different encodings but none of them work. – hklel Sep 13 '15 at 09:22
  • @AlexLing: `let testUrl = NSURL(string: "https://www.google.com/search?q=%20site:%20stackoverflow.com")` with the NSISOLatin1StringEncoding does work for me. The error message *"The file “search” couldn’t be opened"* seems to be unrelated to the encoding to me. – Martin R Sep 13 '15 at 09:27
  • Saved my life!!!! I was trying to download a .svg image as String and persisting it for showing in a WKWebView, even if the user is offline. This finally solved the issue. – GabrielaBezerra Apr 13 '18 at 03:30
2

Swift 3 Solution:

do {

html = try NSString(contentsOf: url, encoding: String.Encoding.isoLatin1.rawValue)

} catch let error {

  print(error)

}
Elon R.
  • 131
  • 1
  • 4
0

Swift 5 Solution:

try! String(contentsOf: URL(string: "https://www.google.com"), encoding: .utf16)
NerdOfCode
  • 215
  • 2
  • 11