H5 calls native

Suppose a scenario where the user clicks on an activity Baner, notifying the native to open an external activity with a new interface like the h5 interface above, We can also in the – (void) webView: (WKWebView *) webView decidePolicyForNavigationAction: (navigationAction WKNavigationAction *) DecisionHandler :(void (^)(WKNavigationActionPolicy)) the decisionHandler is implemented by listening for url changes

Native main logic

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *str = navigationAction.request.URL.absoluteString; If ([STR hasPrefix: @ "showH5"]) {/ / open the h5} decisionHandler (WKNavigationActionPolicyAllow);; }Copy the code

H5 Main logic

The < div > < p onClick = {() = > {window. The location. Href = "showH5: / / data = 1}} > open camera < / p > < / div >Copy the code

We could do the same thing

The first step is to register the listening method showH5 native

/// Initialize webView and set configuration items -(WKWebView*)webView{if (! _webView) { _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration:self.registConfiguration]; _webView.UIDelegate = self; _webView.navigationDelegate = self; If (@ the available (iOS 11.0, *)) { _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } else {} / / whether to allow gestures left slip back at the next higher level, similar to the left of the navigation control slide returns _webView. AllowsBackForwardNavigationGestures = YES; NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http://10.100.12.228:8088/#/"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30]; [_webView loadRequest:request]; } return _webView; } - (WKWebViewConfiguration *)registConfiguration{ WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.userContentController = [WKUserContentController new]; NSArray *methodArr = @[@"showH5"]; NSArray *methodArr = @[@"showH5"]; / / here prior to injection and h5 agreed method name [methodArr enumerateObjectsUsingBlock: ^ (nsstrings * methodStr, NSUInteger independence idx. BOOL * _Nonnull stop) { [configuration.userContentController addScriptMessageHandler:self name:methodStr]; }]; WKPreferences *preferences = [WKPreferences new]; preferences.javaScriptCanOpenWindowsAutomatically = YES; configuration.preferences = preferences; return configuration; }Copy the code

Step 2: H5 calls showH5 and native conventions. H5 should distinguish between iOS and Android when processing

 if(window.webkit){
   window.webkit.messageHandlers.showH5.postMessage(JSON.stringify({"url":"www.baidu.com"}));
 }
Copy the code

Step 3 native in – (void)userContentController:(nonnull WKUserContentController *)userContentController DidReceiveScriptMessage :(nonnull WKScriptMessage *)message to listen on

// listen to h5 call native - (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message { NSString *jsonString= message.body; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];  If ([message.name isEqualToString:@"showH5"]){// Open h5 NSLog(@"%@",message.body); }}Copy the code

Native call to H5

Similar to the above, suppose 1 scenario informs H5 to refresh user token. Updatetoken is the agreed method of communication with front-end H5. 123 is the data to be passed, and the native main logic is usually passed in JSON string

NSString *str = @"updatetoken('123')";
[self.webView evaluateJavaScript:str completionHandler:^(id _Nullable complete, NSError * _Nullable error) {
    if (complete) {
    }
}];
Copy the code

H5 main logic needs to bind methods on Windows

Window. updatetoken =function (STR) {window.data = STR; window.data = STR; }Copy the code