3

I have users logging into a website using a WKWebView after which I want to parse the HTML of the page. I am very much new to Swift/iOS Development (just learning things as I go along). I know the id of the HTML tag I am trying to grab the innerHTML of (the id is "dataGrid") and would like to store the string in a variable called htmlString. I have the following code:

var htmlString = "initial value"
webView.evaluateJavaScript("document.getElementById('dataGrid').innerHTML.toString()", 
    completionHandler: { (html: Any?, error: Error?) in htmlString = html as! String})
print(htmlString)

Evidently this doesn't work - the last print statement just prints "initial value". Just so you know, I am basing my code off of the method described in another StackOverflow post (Get HTML from WKWebview in Swift). In the one, the completion handler has a print statement, which actually works in printing the HTML. However, I don't really understand completion handlers, which makes sense considering I haven't really had much experience with Swift yet, but it also means I don't know how to adapt the code in that post for my own purposes. I would really appreciate it if someone could direct me in the right direction so I can store the HTML of the page as a string in a variable that I can mutate later. Thank you!

  • The code you refer to has the print call into the completion handler. Why did you moved it out of the completion handler? Asking because that's exactly what made your code to not work as expected. – Cristik Sep 02 '18 at 13:13
  • I just wanted to see the value of htmlString afterwards. My end goal is to pull information from the HTML. – Shardul Joshi Sep 02 '18 at 14:19
  • Then keep the print within the completion handler. And add the processing there. – Cristik Sep 02 '18 at 14:20

1 Answers1

2

The value of htmlString is "initial value" because the block is executed after the print statement is getting executed!

If you do print the htmlString inside the block you can see the actual value. You have to do your task inside the completion block. Also the completion block will be executed in the main thread so you need to make sure that you don't block the main thread.

Karthick Ramesh
  • 1,451
  • 20
  • 30