ios h5 上按钮调用原生界面

主要针对WKWebview

001

 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    [config.userContentController addScriptMessageHandler:self name:@"Native"];
    
    [config.userContentController addScriptMessageHandler:self name:@"toTaxRefundCalculation"];   // 方法名一定要和H5开发人员协商定好  self
    [config.userContentController addScriptMessageHandler:self name:@"toPhasedCalculation"];   //切记  方法名一定要和H5开发人员协商定好  self
    [config.userContentController addScriptMessageHandler:self name:@"toNews"];   //切记 消息中心 方法名一定要和H5开发人员协商定好  self

    
    self.wkWebView = [[WKWebView alloc] initWithFrame:frame configuration:config];
    [_wkWebView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [_wkWebView setNavigationDelegate:self];
    [_wkWebView setUIDelegate:self];
    [_wkWebView setMultipleTouchEnabled:YES];
    [_wkWebView setAutoresizesSubviews:YES];
    [_wkWebView.scrollView setAlwaysBounceVertical:YES];
    _wkWebView.scrollView.bounces = NO;
    
    [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkWebBrowserContext];
    [self addSubview:self.wkWebView];

002 处理方法调用原生界面

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"toTaxRefundCalculation"]) {//跳转对应的原生界面
   [self toTaxRefundCalculation];
}else if ([message.name isEqualToString:@"toPhasedCalculation"]){//跳转对应的原生页面
    [self toPhasedCalculation];
}else if([message.name isEqualToString:@"toNews"]){//跳转对应的原生页面
    [self toNews];
}

}

}

003 h5端的配置需要是这样的

window.webkit.messageHandlers.toTaxRefundCalculation.postMessage(@"toTaxRefundCalculation")
window.webkit.messageHandlers.toPhasedCalculation.postMessage(@"toPhasedCalculation")
window.webkit.messageHandlers.toNews.postMessage(@"toNews")

tip: 如果在本地测试可以调用原生,但是切换服务器不可以。此时多是服务器缓存问题,删除clean 卸载app 重新运行就可以了。

你可能感兴趣的:(ios h5 上按钮调用原生界面)