iOS与JS交互之WKWebView-WKScriptMessageHandler协议


前言
  “iOS与JS交互”。iOS指iOS原生代码(文章只有OC示例),JS指WEB前端(不单指JavaScript),交互指JS调用iOSiOS调用JS。将iOS与JS交互总结成了6种方式,并将逐一介绍。
目录如下:
本文介绍如果使用WKWebView的WKScriptMessageHandler实现iOS与JS交互。
WKWebView是Apple在iOS8推出的Webkit框架中的负责网页的渲染与展示的类,相比UIWebView速度更快,占用内存更少,支持更多的HTML特性。WKScriptMessageHandler是WebKit提供的一种在WKWebView上进行JS消息控制的协议。
一、JS调用iOS:
  • 实现逻辑:点击JS的登录按钮,JS将登录成功后的token数据传递给iOS,iOS将收到的数据展示出来。

  • 实现效果:


     
    JS调用iOS实现效果
  • JS代码:

//! 登录按钮
<button onclick = "login()" style = "font-size: 18px;">登录</button>
//! 登录
function login() {
  var token = "js_tokenString";
  loginSucceed(token);
}

//! 登录成功
function loginSucceed(token) {
  var action = "loginSucceed";
  window.webkit.messageHandlers.jsToOc.postMessage(action, token);
}
  • iOS代码:
//! 导入WebKit框架头文件
#import <WebKit/WebKit.h>

//! WKWebViewWKScriptMessageHandlerController遵守WKScriptMessageHandler协议
@interface WKWebViewWKScriptMessageHandlerController () <WKScriptMessageHandler>


//! 为userContentController添加ScriptMessageHandler,并指明name WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addScriptMessageHandler:self name:@"jsToOc"]; //! 使用添加了ScriptMessageHandler的userContentController配置configuration WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.userContentController = userContentController; //! 使用configuration对象初始化webView _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
#pragma mark - WKScriptMessageHandler
//! WKWebView收到ScriptMessage时回调此方法 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) { [WKWebViewWKScriptMessageHandlerController showAlertWithTitle:message.name message:message.body cancelHandler:nil]; } }
  • 实现原理:
    1、JS与iOS约定好jsToOc方法,用作JS在调用iOS时的方法;
    2、iOS使用WKUserContentController-addScriptMessageHandler:name:方法监听namejsToOc的消息;
    3、JS通过window.webkit.messageHandlers.jsToOc.postMessage()的方式对jsToOc方法发送消息;
    4、iOS在-userContentController:didReceiveScriptMessage:方法中读取namejsToOc的消息数据message.body

PS[userContentController addScriptMessageHandler:self name:@"jsToOc"]会引起循环引用问题。一般来说,在合适的时机removeScriptMessageHandler可以解决此问题。比如:在-viewWillAppear:方法中执行add操作,在-viewWillDisappear:方法中执行remove操作。如下:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_webView.configuration.userContentController addScriptMessageHandler:self name:@"jsToOc"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"jsToOc"];
}

 


二、iOS调用JS:

iOS调用JS方式与上篇文章一致,都是通过WKWebView的-evaluateJavaScript:completionHandler:方法来实现的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM