I need to look at the HTML of a page given by a certain URL. If I have this, what is the most efficient and synchronous way to get the HTML source for that URL using Swift?
This is the way to go in Swift 2:
let myURLString = "https://duckduckgo.com/"
if let myURL = NSURL(string: myURLString) {
do {
let myHTMLString = try String(contentsOfURL: myURL, encoding: NSUTF8StringEncoding)
print("HTML : \(myHTMLString)")
} catch {
print("Error : \(error)")
}
} else {
print("Error: \(myURLString) doesn't URL")
}
Also as an extra related to previous answers:
Note that Swift 2 introduces a new error handling approach that produces much clearer code for programmers to read, it does away with complexities like & to pass in NSErrors, and it gives you greater safety by ensuring you catch all errors.
Only use try! if you are 100% sure that the call won't fail.
Further reading: https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch