1

Using Swift, how can I retrieve the HTML Code of a webpage. I have read up on http requests but I cannot figure out how to implement them to fetch the HTML code. Does anyone know how to do this?

Edit: The similar question suggested does not seem to have a working solution.

user1939991
  • 187
  • 4
  • 14

1 Answers1

4

This should do the trick: (adapted from the objective-c in this answer)

let url = NSURL(string: "http://www.example.com")
var error: NSError?
let html = NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding, error: &error)

if (error != nil) {
    println("whoops, something went wrong")
} else {
    println(html!)
}
Community
  • 1
  • 1
cmyr
  • 2,235
  • 21
  • 30