LeeWkWebView 起因
之前我在公众号写了一篇关于 UIWebView 的 JavaScript 与 App 通信的文章,但是根据最新的 iOS 审核规定,需要用 WKWebView 替换 UIWebView 才能通过审核。但是由于之前有很多 UIWebView 的交互,怎么办?于是根据原有的交互经验,我创建了 LeeWKWebView……当然,希望大家能喜欢,多提意见。
使用
pod 'LeeWkWebView',:git=>'[email protected]:skeyboy/LeeWkWebView.git'
之前不是很完善,只是简单介绍了一下,今天我就来完善一下。为了方便 JavaScript 调用识别,我们给我们的句柄起了个名字——npc
mWbHelper = [[WKWebViewHelper alloc] initHanlerNpc:@"iOSApp" frame:[UIScreen mainScreen].bounds];
H5 JavaScript 文件示例
function btnClick() {
try {
iOSApp.shareAction({"title":"分享", "content":"内容", "url":"链接"})
} catch (err) {
alert(err)
}
}
//App主动调用这个传递token
function getToken(token, other){
alert(token);
return other;
}
//JS 主动点击获取
function manualGetToken(){
alert(iOSApp.manualGetToken())
}
function shareLocation(){
alert(App.shareLocation())
}
function getAreaID(token){
alert(token);
return token;
}
function popBack() {
try {
<!-- window.webkit.messageHandlers.popBack.postMessage([])-->
iOSApp.popBack([])
} catch (err) {
alert(err)
}
}
</script>
1 增加Web加载完成时 App 主动给 JS 发信息的功能
在实际项目中,_web 提出的一个功能是,当你 App 加载资源结束后,你需要给我 Web 发送一些信息——token、App 位置信息(经纬度)……
//加载完成后通知JS发送一些消息
mWbHelper.didFinishNavigationHook = ^NSArray<WKActionHandler *> * _Nullable{
NSData * values = [NSJSONSerialization dataWithJSONObject:@{@"token":@"12345"} options:NSJSONWritingFragmentsAllowed
error:nil];
NSString *other = [[NSString alloc] initWithData:values encoding:NSUTF8StringEncoding];
WKActionHandler * tokenHandler = [[WKActionHandler alloc] init];
tokenHandler.name = @"getToken";
tokenHandler.actionParamsName = @[@"2345dcddd",other];
tokenHandler.action = ^(NSDictionary * _Nonnull vales) {
};
return @[
tokenHandler
];
};
2 App 等待接收 Web 通信
这个需要说得比较典型的就是有一天,项目突然提出了,我加载 web 资讯的页面也想增加分享——调用 App 原生进行微信分享。……哈哈,这是什么需求啊,但是我们还是需要满足的
[mWbHelper addAsyncJSHandler:@"shareAction" pramasNames:@[@"title",@"content",@"url"]
result:^(NSDictionary * _Nonnull values) {
}];
再比如,我们使用导航 push 一个页面加载 web,需要让 web 也能通知 App 进行 pop
[mWbHelper addAsyncJSHandler:@"popBack" pramasNames:@[] result:^(NSDictionary * _Nonnull values) {
}];
```
## 3 通过人工操作App调用JS
项目中我们除了遇到上面两种被动的,也会遇到需要我么通过触动UI实现App调用web进行通信的情况,此时我们怎么做呢?🌰是我们通过点击button实现了App与JS的通信
-
(IBAction)manualCallJs:(id)sender {
WKActionHandler * tokenHandler = [[WKActionHandler alloc] init]; tokenHandler.name = @"getToken"; tokenHandler.actionParamsName = @[@"2345dcddd",[NSString stringWithFormat:@"%s",__func__]]; tokenHandler.action = ^(NSDictionary * _Nonnull vales) { };
[mWbHelper manualAppCallJS:tokenHandler];
}
## 4 最后是加载web对应的url啦
我们以加载本的一个HTML为例
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
WKWebView * webView = [mWbHelper buildWithurl:[NSURL fileURLWithPath:path]];
