iOS下JS与原生的交互二

Posted LiLM

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS下JS与原生的交互二相关的知识,希望对你有一定的参考价值。

本篇主要讲的是UIWebView和JS的交互,UIWebView和JS交互的详解https://www.cnblogs.com/llhlj/p/6429431.html

一. WKWebView调用JS

[webView evaluatejavascript:@"我是JS" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  
}];

该方法为异步执行

 

二.JS调用OC

当JS端想传一些数据给ios.那它们会调用下方方法来发送.

window.webkit.messageHandlers.<对象名>.postMessage(<数据>)

上方代码在JS端写会报错,导致页面后面业务不执行.可使用try-catch执行.

那么在OC中的处理方法如下.它是WKScriptMessageHandler的代理方法.name和上方JS中的对象名相对应.

- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;

具体添加如下

1.设置addScriptMessageHandler的代理和名称

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        
        [userContentController addScriptMessageHandler:self name:@"对象名"];
        
        configuration.userContentController = userContentController;
        //
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
//        preferences.minimumFontSize = 40.0;
        configuration.preferences = preferences;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT64) configuration:configuration];

2.WKScriptMessageHandler协议方法

- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    //js调用oc
    if ([message.name isEqualToString:@"对象名"]) {
        //具体逻辑
        NSLog(@"---------%@",message.body);//message.boby就是JS里传过来的参数
    }
}

3.销毁

- (void)dealloc {
    ...
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"对象名"];
    ...
}

 

以上是关于iOS下JS与原生的交互二的主要内容,如果未能解决你的问题,请参考以下文章

iOS WKWebView JS 与 原生交互小结

Vue框架下 JS与native的交互(iOS&Android)

iOS JS与原生交互(全集)

WebViewJavascriptBridge实现js与android和ios原生交互

RN系列:Android原生与RN如何交互通信

VUE 与 原生交互(iOS为主)