JavaMaMocha
JavaMaMocha

Reputation: 70

Swift Retrieve HTML data from Webview

I am trying to obtain the data within the header of a web page that is being displayed in a UIWebView.

How do I get the raw (unformatted) HTML string from the UIWebView?

Also, I'm using iOS 9.

My question is similar to Reading HTML content from a UIWebView , but this post is from 6 years ago.

Upvotes: 0

Views: 9566

Answers (3)

Chris Ho
Chris Ho

Reputation: 295

Don't forgot get the html when the page render finished, if you got html too early, the result will be empty.

func webViewDidFinishLoad(webView: UIWebView) {
     print("pageDidFinished")
     if let html = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML") {
             print("html=[\(html)]")
      }

}

Upvotes: 0

ingconti
ingconti

Reputation: 11646

swift 4:

if let html = self.webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){

}

Upvotes: 0

Andrew
Andrew

Reputation: 15377

From the top answer on the question you linked:

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: 
                                     @"document.body.innerHTML"];

would translate into Swift:

let html = yourWebView.stringByEvaluatingJavaScriptFromString("document.body.innerHTML")

stringByEvaluatingJavaScriptFromString returns a optional, so you'd probably want to later use an if let statement:

if let page = html {
    // Do stuff with the now unwrapped "page" string
}

Upvotes: 4

Related Questions