TurboPascal
TurboPascal

Reputation: 79

swift how to use getelementsbytagname to return a value

I am a novice Swift 3.x programmer and I am trying to convert an AppleScript program to Swift that scrapes data from a website using WebKit in Cocoa (iMac desktop). The function VCgetInputByTag looks for html tag (theTag) and is suppose to return the text for that tag. When I try to use this function, the print("text= (response)") displays the data I want but I can't get the function VCgetInputByTag to return that string. Please advise.

func VCgetInputByTag(theTag : String, num : Int) -> String {

  var webTagText : String

  webTagText = ""


  webView.evaluateJavaScript("document.getElementsByTagName('\(theTag)')[\(num)].innerHTML;") {(response:Any?, error:Error?) in
     if (response != nil) {
        webTagText = response as! String
        webTagText = "\(response)"
        print("text= \(response)")
     }
     // error handling
  }



  print(webTagText)
  return webTagText

}

The AppleScript version that I use and works is

to getInputByTag(theTag, num) -- defines a function with two inputs, theTag and num

tell application "Safari" --tells AS that we are going to use Safari

    set input to do JavaScript "document.getElementsByTagName('" & theTag & "')[" & num & "].innerHTML;" in document 1

end tell

return input

end getInputByTag

Thanks to all in advance for your help.

Upvotes: 0

Views: 1200

Answers (1)

Santhosh R
Santhosh R

Reputation: 1568

The evaluateJavaScript function is asynchronous, so you cannot return the resulting string from VCgetInputByTag function synchronously. What you need is a completion handler to return the result asynchronously.

func VCgetInputByTag(theTag : String, num : Int, completionHandler:@escaping (_ result:String)->Void){

    webView.evaluateJavaScript("document.getElementsByTagName('\(theTag)')[\(num)].innerHTML;") {(response:Any?, error:Error?) in
      if let result = response as? String{
         print("text= \(response)")
         completionHandler(result)
      }
       // error handling
    }
}

Upvotes: 0

Related Questions