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:@"对象名"];
    ...
}

 

posted @ 2017-03-03 11:12  LiLM  阅读(361)  评论(0编辑  收藏  举报