iOS与H5交互(WKWbebView)
前言:
在ios开发中,或多或少的会嵌入一些h5页面,有时候需要原生代码和h5页面进行交互。ios8开始苹果推出性能更强大的wkwebview,所以一下方法是关于wkwebview与js的交互。
创建wkwebview:
遵守协议
<wknavigationdelegate, wkuidelegate, wkscriptmessagehandler>
-(wkwebview *)wkwebview
{
if (!_wkwebview) {
_wkwebview = [[wkwebview alloc] initwithframe:cgrectmake(0, heightsignal, screenwidth, screenheight-heightsignal-heightbottomsafe)];
_wkwebview.scrollview.backgroundcolor = [uicolor whitecolor];
_wkwebview.navigationdelegate = self;
_wkwebview.uidelegate = self;
[self.view addsubview:_wkwebview];
}
return _wkwebview;
}
顶部网页加载进度条:
self.progressview = [[uiprogressview alloc] initwithframe:cgrectmake(0, heightsignal, [[uiscreen mainscreen] bounds].size.width, 2)];
self.progressview.backgroundcolor = [uicolor bluecolor];
//设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.
self.progressview.transform = cgaffinetransformmakescale(1.0f, 1.5f);
[self.view addsubview:self.progressview];
[self.wkwebview addobserver:self forkeypath:@"estimatedprogress" options:nskeyvalueobservingoptionnew context:nil];//进度监听
#pragma mark 加载进度监听
- (void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary<nsstring *,id> *)change context:(void *)context {
if ([keypath isequaltostring:@"estimatedprogress"]) {
self.progressview.progress = self.wkwebview.estimatedprogress;
if (self.progressview.progress == 1) {
/*
*添加一个简单的动画,将progressview的height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍
*动画时长0.25s,延时0.3s后开始动画
*动画结束后将progressview隐藏
*/
__weak typeof (self)weakself = self;
[uiview animatewithduration:0.25f delay:0.3f options:uiviewanimationoptioncurveeaseout animations:^{
weakself.progressview.transform = cgaffinetransformmakescale(1.0f, 1.4f);
} completion:^(bool finished) {
weakself.progressview.hidden = yes;
}];
}
}else{
[super observevalueforkeypath:keypath ofobject:object change:change context:context];
}
}
添加js事件监控:
-(void)viewwillappear:(bool)animated
{
[super viewwillappear:animated];
[self.wkwebview.configuration.usercontentcontroller addscriptmessagehandler:self name:@"share"];//分享
}
移除js事件监控:
-(void)viewwilldisappear:(bool)animated
{
[super viewwilldisappear:animated];
[self.wkwebview.configuration.usercontentcontroller removescriptmessagehandlerforname:@"share"];//分享
}
监听方法:
-(void)usercontentcontroller:(wkusercontentcontroller *)usercontentcontroller didreceivescriptmessage:(wkscriptmessage *)message
{
if ([message.name isequaltostring:@"share"]) {
}
}