1

I am trying to get the html code of the webpage using following code :-

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

if (error != nil) {
    print("whoops, something went wrong")
} else {
    print(html!)
}

But i am getting following error in line number 3 ( let html = ....) :-

Argument labels '(contentsOfURL:, encoding:, error:)' do not match any available overloads
1

2 Answers 2

1

The function is NSString(contentsOfURL url: NSURL, encoding enc: UInt) throws

Your code should look like this:

if let url = NSURL(string: "http://www.example.com") {
    do {
        let html = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)
        print(html)
    } catch {
        print("whoops, something went wrong")
    }
}

For more information, take a look at the new way of handling errors in Swift.

UPDATE

Used with your URL:

if let url = NSURL(string: "http://www.police.gov.bd/career_child.php?id=247%20order%20by%201--") {
    do {
        let html = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)
        print(html)
    } catch {
        print("whoops, something went wrong")
    }
}

UPDATE 2:

To autodetect the encoding see this answer

Sign up to request clarification or add additional context in comments.

10 Comments

always executing catch, not executing do
@shubhammishra If I execute that code in playground, I get the html content printed. Make sure the URL you use is correct (and has the scheme prefix, such as http://or https://)
police.gov.bd/career_child.php?id=247%20order%20by%201-- this url works fine in browser but fails to do so using above
You have to use http://www.police.gov.bd/career_child.php?id=247%20order%20by%201--, without http it is not well formatted
Because it is NSISOLatin1StringEncoding, not NSISOLatinStringEncoding. When I use the code above with that encoding and your url it works fine. PS: I also added a new edit for autodetecting the encoding
|
1

Use below code:

if let url = NSURL(string: "http://www.example.com") {
    do {
        let myHTMLString = try String(contentsOfURL: url, encoding: NSUTF8StringEncoding)
    } catch let error as NSError {
        print("Error: \(error)")
    } catch {
        print("failure")
    }
}

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.