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?

5
  • oh nvm, changing encoding: NSUTF8StringEncoding to encoding: NSASCIIStringEncoding solve it :) Commented Sep 13, 2015 at 8:45
  • stackoverflow.com/questions/26453711/… This guy had a similar error. Commented Sep 13, 2015 at 8:47
  • would you please mention what version of xcode you are using Commented Sep 13, 2015 at 9:12
  • @AlexLing: NSASCIIStringEncoding cannot represent any non-ASCII characters. So even if it does not crash, NSASCIIStringEncoding is almost always a bad choice. Commented Sep 13, 2015 at 9:18
  • @jamil65able I am using Xcode 7.0 GM Commented Sep 13, 2015 at 9:19

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, it works but when I tried another url like 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.
@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.
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.
2

Swift 3 Solution:

do {

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

} catch let error {

  print(error)

}

Comments

0

Swift 5 Solution:

try! String(contentsOf: URL(string: "https://www.google.com"), encoding: .utf16)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.