Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating responsive html webpages in native iOS app and communicate using Apache Cordova

I have a native application built in swift 3.0.Now there is a requirement to load some responsive webpages inside our app.After loading the webpages ,if any action is taken on those pages, some changes to be made in our native code for displaying some requirement.Heard about Apache Cordova for achieving this.But not getting a proper tutorial to understand the process.Please help

like image 897
Vork Avatar asked Nov 30 '25 02:11

Vork


1 Answers

If your methods are somewhat limited and known, you can use WKWebView's message handler callbacks to call from a javascript function. Then some native code executes to which you can send basic data.

What you need to acomplish for that:

let contentController = WKUserContentController()
contentController.add(self, name: "nativeCallbackIOS")

let config = WKWebViewConfiguration()
config.userContentController = contentController

let webView = WKWebView(frame: .zero, configuration: config)

whatever is "self" needs to implement WKScriptMessageHandler like this:

extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "nativeCallbackIOS" {
            // do your native stuff here
        }
    }
}

In your website javascript you will call it like that:

window.webkit.messageHandlers.nativeCallbackIOS.postMessage()

If you need to pass arguments you need to define your specification, because the message.body on the WKScriptMessageHandler is of type "Any". In general, a json type would be a smart idea because you can then use either jsonserialization or codable (if you upgrade your swift version, recommended).

Hint: syntax used in examples above is swift 5, so method names could differ.

like image 188
MartinM Avatar answered Dec 02 '25 14:12

MartinM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!