Reputation: 4025
let myURLString = "https://en.wiktionary.org/wiki/see"
if let myURL = NSURL(string: myURLString) {
let myHTMLString = String(contentsOfURL: myURL, encoding: String.Encoding.utf8)
print("HTML : \(myHTMLString)")
}
And I got printed:
HTML : (https://en.wiktionary.org/wiki/see, Unicode (UTF-8))
But instead I need html content. What I am doing wrong?
Update:
As a source for the code I used: How To Get HTML source from URL with Swift
Please, read my question with more attention, as the result I got text of link, but instead I need text of html page
Upvotes: 3
Views: 10175
Reputation: 59496
To retrieve the HTML of the webpage referenced by a url you just need to
let myURLString = "https://en.wiktionary.org/wiki/see"
if let
url = NSURL(string: myURLString),
html = try? String(contentsOfURL: url) {
print(html)
}
I tested this code in my Playground and it is retrieving the full HTML of the web page.
Upvotes: 1
Reputation: 4025
Solution: instead of String, use NSString
let myURLString = "https://en.wiktionary.org/wiki/see"
if let myURL = NSURL(string: myURLString) {
do {
let myHTMLString = try NSString(contentsOf: myURL as URL, encoding: String.Encoding.utf8.rawValue)
print("html \(myHTMLString)")
} catch {
print(error)
}
}
Upvotes: 0
Reputation: 4795
Try this:
let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOfURL: myURL)
print("HTML : \(myHTMLString)")
} catch let error as NSError {
print("Error: \(error)")
}
Hope this helps!
Upvotes: 3