iOS與H5交互(WKWbebView)

前言:

在iOS開發(fā)中,或多或少的會嵌入一些H5頁面,有時候需要原生代碼和H5頁面進行交互。iOS8開始蘋果推出性能更強大的WKWebView,所以一下方法是關于WKWebView與JS的交互。

創(chuàng)建WKWebView:

遵守協(xié)議

-(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;

}

頂部網(wǎng)頁加載進度條:

self.progressView?= [[UIProgressView?alloc] initWithFrame:CGRectMake(0,?HeightSignal, [[UIScreen?mainScreen] bounds].size.width,?2)];

?self.progressView.backgroundColor?= [UIColor?blueColor];

? ? //設置進度條的高度,下面這句代碼表示進度條的寬度變?yōu)樵瓉淼?倍,高度變?yōu)樵瓉淼?.5倍.

?self.progressView.transform?= CGAffineTransformMakeScale(1.0f,?1.5f);

[self.view?addSubview:self.progressView];

[self.wkwebview?addObserver:self?forKeyPath:@"estimatedProgress"?options:NSKeyValueObservingOptionNew?context:nil];//進度監(jiān)聽

#pragma mark 加載進度監(jiān)聽

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

?if?([keyPath?isEqualToString:@"estimatedProgress"]) {

?self.progressView.progress?=?self.wkwebview.estimatedProgress;

?if (self.progressView.progress ==?1) {

?/*

?? ? ? ? ? ? *添加一個簡單的動畫,將progressView的Height變?yōu)?.4倍,在開始加載網(wǎng)頁的代理中會恢復為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事件監(jiān)控:

-(void)viewWillAppear:(BOOL)animated

{

[super?viewWillAppear:animated];

[self.wkwebview.configuration.userContentController?addScriptMessageHandler:self?name:@"share"];//分享

}

移除JS事件監(jiān)控:

-(void)viewWillDisappear:(BOOL)animated

{

[super?viewWillDisappear:animated];

[self.wkwebview.configuration.userContentController?removeScriptMessageHandlerForName:@"share"];//分享

}

監(jiān)聽方法:

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

{

?if ([message.name?isEqualToString:@"share"]) {

? ? ? ? }

}

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容