Home Evaluating javascript function from swift, getting nil in the completion handler
Reply: 1

Evaluating javascript function from swift, getting nil in the completion handler

MBN Published in 2018-02-14 08:53:23Z

In my iOS app, i am loading a url in WKWebView, and on a native iOS button click i am calling a javascript function to execute. I am using the following method to execute the function.

let result = webView.evaluateJavaScript("saveUserTemplate()", completionHandler: {(response, error) in

            print(response as Any) 
            print(error as Any)


Now, the problem is, when the completion handler is fired, i am getting the response and error both as nil.

Please suggest some way to get the response from the java script function.

MBN Reply to 2018-02-15 10:59:57Z

I was not getting the response from evaluateJavaScript function, because of the ajax call at server side and the javascript function was not waiting for the completion of execution of the ajax call.

The issue is solved using script messages of wkWebview.

I created the configuration for webview and added the contentController in the config.

let contentController = WKUserContentController()
contentController.add(self, name: "cardSaved")
let config = WKWebViewConfiguration()
config.userContentController = contentController

webView = WKWebView(frame: CGRect(x: 10 , y : 10, width : UIScreen.main.bounds.width - 20, height : view.bounds.height - 150), configuration : config)

The handler is fired from javascript function, like :

webkit.messageHandlers.cardSaved.postMessage("Card Saved Succesfully");

Once the event is fired from javascript side, my delegate method is fired:

//MARK: - WKScriptMessageHandler Methods

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
        if message.name == "cardSaved" {
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300833 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO