Skip to content
Advertisement

WebKit userContentController:didReceiveScriptMessage: not getting called for iOS 13

I am using WKWebView for showing web content into my app but I am not able to get a message sent from JS webkit on iOS 13 devices.
On previous iOS versions, it’s working as expected.

Setup:

func setupWebView() {
    let config: WKWebViewConfiguration = WKWebViewConfiguration()
    config.userContentController.add(self, name: "mobileApp")
    webView = WKWebView(frame: self.view.frame, configuration: config)
    webView?.navigationDelegate = self
    webView?.uiDelegate = self
    webView?.scrollView.bounces = false
    webView?.backgroundColor = UIColor.clear

    self.view.addSubview(webView!)
    self.webView?.load(URLRequest(url: URL(string: self.stringURL!)!))
}

WKScriptMessageHandler Delegate:

func userContentController(_ userContentController: WKUserContentController, 
                                didReceive message: WKScriptMessage) {
    let data = NSMutableDictionary(dictionary: message.body as! Dictionary)
    //Method is not getting called
}

From JavaScript I am calling it like this :

webkit.messageHandlers.mobileApp.postMessage({ 'backToApp': '1' });

Please let me know if anyone has come across this issue and some possible solution to it.

Advertisement

Answer

After lots of searching, I found the solution that in iOS 13 user agent property is changed which we were used in WEB to check if it is mobile or not. isMobile check was failing because of that our message handler was not getting called.

A lot of breaking changes have been done in iOS 13 that currently we need to take care.

Advertisement