javascript - Return HTML string from the completion handler of the evaluateJavaScript function -


i know i'm not first 1 ask can't solve problem. i'm trying take piece of string html using evaluatejavascript in xcode swift 3 , piece of text called value inside completion handler, did this:

var username = string()     func takedata() {         webview.evaluatejavascript("document.queryselectorall('.name')[0].innerhtml") { (value, error) in              if let valuename = value as? string {                 self.username = valuename             }             print(value)             print(error)         }      }  print(" name : \(self.username)")  

the problem console prints: name ()

the problem printing value before asynchronous function finish execution. have several solutions solve issue. can either implement takedata have completionhandler 1 of input parameters, use gcd make statements execute in expected order or use 3rd party library, such promisekit handle async requests you, behave normal functions return value.

i give example completion handler:

func takedata(completionhandler: @escaping (_ username: string?) -> void){     webview.evaluatejavascript("document.queryselectorall('.name')[0].innerhtml") { (value, error) in         if let valuename = value as? string {             completionhandler(valuename)         }         print(value)         print(error)         completionhandler(nil)     } } 

you use value completionhandler this:

takedata(completionhandler: { username in     print(username) }) 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -