1

I am downloading HTML source code of a webpage this way:

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!)
}

But I would like to get it as String instead of NSString. Is there any way?

1 Answer 1

1

Swift's String also accepts the same initializer:

let html = String(contentsOfURL: url!, encoding: NSUTF8StringEncoding, error: &error)

I would suggest to use safe unwrapping with if let for your values:

var error: NSError?
if let url = NSURL(string: "http://www.example.com"), let html = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) {
    if error != nil {
        println(error)
    } else {
        println(html)
    }
}

Last note: no need to use brackets around the condition in Swift.


Update for Swift 2 (Xcode 7)

if let url = NSURL(string: "http://www.example.com"),
    let html = try? String(contentsOfURL: url, encoding: NSUTF8StringEncoding) {
        print(html)
}
Sign up to request clarification or add additional context in comments.

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.