Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from Javascript to Swift within a WKWebView?

I am trying to pass data from my sites Javascript to my app, written in Swift.

Javascript:

var messgeToPost = {
     "username": "testing123"
};
window.webkit.messageHandlers.loginSuccess.postMessage(messgeToPost);

Swift:

var webConfig:WKWebViewConfiguration {
    get {
        var webCfg:WKWebViewConfiguration = WKWebViewConfiguration()

        var userController:WKUserContentController = WKUserContentController()

        userController.addScriptMessageHandler(self, name: "loginSuccess")

        webCfg.userContentController = userController;

        return webCfg;
    }
}

override func viewDidLoad() {
     var userController:WKUserContentController = WKUserContentController()
     userController.addScriptMessageHandler(self, name: "loginSuccess")
     webView = WKWebView(frame: self.view.frame,
        configuration: webConfig)
     webView.loadRequest(NSURLRequest(URL: NSURL(string: URLPath)!))
}

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
    if let messageBody:NSDictionary = message.body as? NSDictionary {
        let password:String = messageBody["password"] as! String

        print(password)
    }
}

Unfortunately, print(password) is never called.

What am I missing here?

like image 266
Fizzix Avatar asked Feb 23 '16 10:02

Fizzix


1 Answers

var messgeToPost = {
     "username": "testing123",
     "password": "password"
};

forgot to add password

like image 193
picaso Avatar answered Oct 11 '22 05:10

picaso