hklel
hklel

Reputation: 1634

Swift get HTML from URL

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?

Upvotes: 1

Views: 5234

Answers (3)

NerdOfCode
NerdOfCode

Reputation: 235

Swift 5 Solution:

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

Upvotes: 0

Elon R.
Elon R.

Reputation: 131

Swift 3 Solution:

do {

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

} catch let error {

  print(error)

}

Upvotes: 2

Martin R
Martin R

Reputation: 539745

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.

Upvotes: 7

Related Questions