前言: 根据需求有时候需要用到JS与Objective-C
交互来实现一些需求, 本文介绍实现交互的一种方式, 使用WKWebView
的新特性MessageHandler
, 来实现JS调用原生, 原生调用JS.
WKWebView 初始化时,有一个参数叫configuration,它是WKWebViewConfiguration类型的参数,而WKWebViewConfiguration有一个属性叫userContentController,它又是WKUserContentController类型的参数。WKUserContentController对象有一个方法- addScriptMessageHandler:name:,我把这个功能简称为MessageHandler。- addScriptMessageHandler:name:有两个参数,第一个参数是userContentController的代理对象,第二个参数是JS里发送postMessage的对象。
所以要使用MessageHandler功能,就必须要实现WKScriptMessageHandler协议。
###二. 在JS中使用方法
function locationClick() {/// "showMessage". 为我们和前端开发人员的约定ssageHandlers.showMessage.postMessage(null);}
2.1 对WKWebView进行初始化以及设置
/// 创建网页配置对象WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];/// 创建设置对象WKPreferences *preference = [[WKPreferences alloc]init];/// 最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果preference.minimumFontSize = 40.0;/// 设置是否支持javaScript 默认是支持的preference.javaScriptEnabled = YES;/// 在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口preference.javaScriptCanOpenWindowsAutomatically = YES;config.preferences = preference;/// 这个类主要用来做native与JavaScript的交互管理_wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:config];[self.view addSubview:_wkwebView];/// Load WebView
#if 0NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];[self.wkwebView loadRequest:request];
#endif#if 1NSString *bundleStr = [[NSBundle mainBundle] pathForResource:@"summerxx-test" ofType:@"html"];[self.wkwebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:bundleStr]]];
#endif// UI代理_wkwebView.UIDelegate = self;// 导航代理_wkwebView.navigationDelegate = self;// 是否允许手势左滑返回上一级, 类似导航控制的左滑返回_wkwebView.allowsBackForwardNavigationGestures = YES;// 添加监测网页加载进度的观察者[self.wkwebView addObserver:selfforKeyPath:@"estimatedProgress"options:0context:nil];// 添加监测网页标题title的观察者[self.wkwebView addObserver:selfforKeyPath:@"title"options:NSKeyValueObservingOptionNewcontext:nil];
2.2 在合理地方进行注册
[figuration.userContentController addScriptMessageHandler:self name:@"showMessage"];
2.3 接收JS给我们传递消息, 这里我做了一个简单的弹窗提示
#pragma mark - WKScriptMessageHandler
/// 通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{if ([message.name isEqualToString:@"showMessage"]) {UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"messgae" preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"同意" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"虽然我同意了你, 但是答应我别骄傲."];[self.wkwebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {NSLog(@"%@----%@",result, error);}];}];UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {NSLog(@"cancel");}];UIAlertAction *errorAction = [UIAlertAction actionWithTitle:@"拒绝" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"虽然我拒绝了你, 但是继续爱我好吗"];[self.wkwebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {NSLog(@"%@----%@",result, error);}];}];[alertController addAction:errorAction];[alertController addAction:okAction];[alertController addAction:cancelAction];// 出现[self presentViewController:alertController animated:YES completion:^{}];}
}
2.3 销毁
- (void)dealloc {/// Remove removeObserver[_wkwebView removeObserver:selfforKeyPath:NSStringFromSelector(@selector(estimatedProgress))];[_wkwebView removeObserver:selfforKeyPath:NSStringFromSelector(@selector(title))];WKUserContentController *userCC = figuration.userContentController;[userCC removeScriptMessageHandlerForName:@"showMessage"];
}
Demo: 演示步骤, 点击获取定位 Objective-C获取到JS消息
点击拒绝, JS获取到Objective-C传递的消息
如图:
总结: 脑壳疼
参照 :
demo: 之后传
完~
文/夏天然后
本文发布于:2024-01-28 16:09:15,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064293618622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |