At present, native apps are mainly divided into IOS and Android. There’s nothing to be said for IOS, an operating system created exclusively by Apple to compete with Google’s Android operating system. Other xiaomi MIUI, Smartisan OS and so on are based on Android, that is to say, the underlying is Still Android.

Of course, now the front end is hot, followed by H5 and APP interaction more and more frequent, H5 to call the APP native method how to operate, APP to call the H5 method and how to operate? Next, we will explain them all!

H5IOSinteraction

Disclaimer: Since I am not engaged in IOS APP development, I can only consult the students of IOS APP development here. I hope you can point out any mistakes.

Because the IOS APP here is developed with ReactiveCocoa. So what exactly is ReactiveCocoa? IOS APP development is a new framework for IOS and OS development developed by Github. Cocoa is short for Apple’s entire framework, so many Apple frameworks like to end in Cocoa. You can go to the specific research.

Now, here’s the thing!!

1, H5 tune APP

IOS APP
/ *! @abstract Adds a script message handler. @param scriptMessageHandler The message handler to add. @param name The name of  the message handler. @discussion Adding a scriptMessageHandler adds afunction
     window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
     frames.
    */
    open func add(_ scriptMessageHandler: WKScriptMessageHandler, name: String)
Copy the code

To add a message script handler, pass the first argument to the added message handler and the second argument to the name of the added message handler.

private (setLazy var webView: WKWebView = {// Initialize a WKWebViewConfigurationlet configuretion = WKWebViewConfiguration()
    configuretion.preferences = WKPreferences()
    configuretion.preferences.javaScriptEnabled = true
    configuretion.preferences.javaScriptCanOpenWindowsAutomatically = false/ / in the configuretion userContentController register message processing method configuretion. UserContentController = WKUserContentController () / uploadImage/registration methods configuretion. UserContentController. Add (self, name: MessageHandlerName. UploadImage. RawValue)/login/registration method configuretion. UserContentController. Add (self, name: MessageHandlerName. Login. RawValue)/home/registration method configuretion. UserContentController. Add (self, name: MessageHandlerName. Home. RawValue) / / initializes a WKWebView and configuration parameters into thelet view = WKWebView.init(frame: .zero, configuration: configuretion)

    return view
}()
Copy the code
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    let name = MessageHandlerName.init(rawValue: message.name)
    
    switch name {
    case.uploadImage? Get the parameters passed by h5 via message.bodyif let uploadType = message.body as? String {
            imageType = uploadType
        }
        
        // do your something
    case.login? : / /do your something
    case.home? : / /do your something
    default:
        break}}Copy the code
H5
window.webkit.messageHandlers.zrbCallUpload.postMessage(this.type)
window.webkit.messageHandlers.login.postMessage(true)
window.webkit.messageHandlers.home.postMessage(true)
Copy the code

Window. Its. MessageHandlers APP environment registration message processing module

ZrbCallUpload APP registered a specific method to listen for messages

The call here is a mandatory pass parameter.

2. Adjust APP H5

The most important point for APP to call H5 method is to concatenate the returned parameters.

APP
let js = "callUploadHtml(\(JSONString!) , \"\(self.imageType!) \ ")"
self.webView.evaluateJavaScript(js, completionHandler: { (_, _) in
                    
})
Copy the code

Note: The string must be enclosed in quotes, otherwise the call will fail.

H5
    window.callUploadHtml = function(dataObj, uploadType){
        //do your something
    };
Copy the code

Note:

  • 1.H5defineAPPThe invoked method must be inwindowGlobal, otherwiseAPPCan’t call
  • 2 here,H5The accepted parameters must be andAPPThere is a one-to-one correspondence between the parameters passed by the call.

The demo address can check https://github.com/littleLane/cross_ios_h5

The H5 interacts with Android

1, H5 tune APP

APP
    webView = (WebView) findViewById(R.id.web_H5Activity);
    progressBar = (ProgressBar) findViewById(R.id.progressBar_h5show);

    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new JavaScriptObject(), "postMessage");
Copy the code

The code on the APP side is basically like this, get the webView and set setJavaScriptEnabled to true and add the addJavascriptInterface listener, Set up global JavaScript methods to handle postMessage.

Next, define a JavaScriptObject class and add the methods you want to handle JavaScript calls to it, as shown in the following example:

Class JavaScriptObject {@javascriptInterface // Upload profile picture public void zrbCallUpload(String paramer, StringreturnFun) {
        //doPublic void zrbLogin(Object Paramer) {// TODO: 2018/1/11 //do your something
    }
    
    ....
}
Copy the code

Now that the APP is done, it’s up to the front end to deal with it!

H5
window.postMessage.zrbCallUpload(param1, param2);
window.postMessage.zrbLogin(param1);
Copy the code

The above two lines of code are the H5 APP. Although it looks simple, there are a few points to note:

  • 1. The method followed by window must be a listening method defined by APP, in this case postMessage

  • 2. Listen to the postMessage method followed by the specific logic call method, here are zrbCallUpload and zrbLogin respectively

  • 3. The parameters sent here must be determined and consistent with the APP, no matter the number or type of parameters. (You’d better, or who knows what could go wrong)

The H5 APP

H5

On the H5 side, you have to define the method on the global window that your APP is going to call.

window.callUploadBack = function(params){
    // do your something
}
Copy the code

The function name must be the same as the one called by APP, and the parameters passed must be the same, no matter the number of parameters or the type of parameters. (You’d better, or who knows what could go wrong)

APP
String js = "javascript:" + returnFun + "(" + params + ");";

webView.loadUrl(js);
Copy the code
  • The name of the function called by returnFun

  • Params returns parameters

The way it’s handled here is that when H5 calls the APP method it passes the method that needs the APP callback, and if it doesn’t need the APP callback it doesn’t need to be passed. The APP then concatenates the JavaScript code to call back H5 based on this parameter, like the code above.