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?
var messgeToPost = {
"username": "testing123",
"password": "password"
};
忘了添加密码
链接地址: http://www.djcxy.com/p/90404.html