WKWebView的簡(jiǎn)單使用方法(包含OC和JS交互處理)

因?yàn)轫?xiàng)目需要,需要原生頁(yè)面和h5交互調(diào)用,WKWebView提供了非常豐富的代理方法,參考了各位大神的詳解,記錄下方便以后查詢。

1、使用方法,具體代碼如下(需要#import <WebKit/WebKit.h>,實(shí)現(xiàn)代理:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler):1.1、定義

@property (nonatomic,strong) WKWebView *webView;

@property(nonatomic,strong)WKUserContentController*userContentController;

@property (nonatomic,strong) UIProgressView *progressView;

1.2、實(shí)現(xiàn)

//設(shè)置一些基礎(chǔ)參數(shù)

WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];

//設(shè)置OC和JS交互調(diào)用方法等

self.userContentController = [[WKUserContentController alloc] init];

conf.userContentController = self.userContentController;

//注冊(cè)方法(當(dāng)原生需要和h5互相調(diào)用的時(shí)候,需要約定調(diào)用方法,h5調(diào)用后回調(diào)),可以注冊(cè)多個(gè)方法[self.userContentController addScriptMessageHandler:self name:@"jumpToCashVC"];

self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, HMC_ScreenWidth, HMC_ScreenHeight+App_View_Orgin_Y - 64) configuration:conf];

self.webView.UIDelegate = self;

self.webView.navigationDelegate = self;

[self.view addSubview:self.webView];

//加載網(wǎng)頁(yè)地址

[self.webView loadRequest:[NSURLRequest requestWithURL:url]];

//添加kvo監(jiān)聽(tīng),加載進(jìn)度值

[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

//添加KVO監(jiān)聽(tīng)

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

//加載進(jìn)度值

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

{

if(object ==self.webView)

{

[self.progressView setAlpha:1.0f];

[self.progressView setProgress:self.webView.estimatedProgress animated:YES];

if(self.webView.estimatedProgress >= 1.0f)

{

[UIView animateWithDuration:0.5f

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? delay:0.3f

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? options:UIViewAnimationOptionCurveEaseOut

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?animations:^{? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[self.progressView setAlpha:0.0f];

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } completion:^(BOOL finished) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[self.progressView setProgress:0.0f animated:NO];

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }];

? ? ? ? ? ? }

? ? ? ? } else {

? ? ? ? ? ? [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

? ? ? ? }

? ? }else{

? ? ? ? [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

? ? }

}

#pragma mark - WKNavigationDelegate

// 頁(yè)面開(kāi)始加載時(shí)調(diào)用

- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation{

? ? self.progressView.hidden = NO;

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

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

}

// 當(dāng)內(nèi)容開(kāi)始返回時(shí)調(diào)用

- (void)webView:(WKWebView*)webView didCommitNavigation:(WKNavigation*)navigation{

}

// 頁(yè)面加載完成之后調(diào)用

- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{

//加載完成后隱藏progressView

self.progressView.hidden = YES;

//加載完成web后可以傳值給h5,通過(guò)如下方法

//jsStr 包含:method(參數(shù))

[self.webView?evaluateJavaScript:jsStr?completionHandler:^(id?_Nullable?result,?NSError?*?_Nullable?error) {

//此處可以打印error.

}];

//h5調(diào)用的時(shí)候只需要實(shí)現(xiàn)這個(gè)方法,獲取對(duì)應(yīng)參數(shù)即可

funtion??method(參數(shù)){

}

}

// 頁(yè)面加載失敗時(shí)調(diào)用

- (void)webView:(WKWebView*)webView didFailProvisionalNavigation:(WKNavigation*)navigation{

? ? //加載失敗同樣需要隱藏progressView

? ? self.progressView.hidden = YES;

? ? [self.webView removeFromSuperview];

}

// 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用

- (void)webView:(WKWebView*)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation*)navigation{

}

// 在收到響應(yīng)后,決定是否跳轉(zhuǎn)

- (void)webView:(WKWebView*)webView decidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler{

? ? DDLog(@"%@",navigationResponse.response.URL.absoluteString);

? ? //允許跳轉(zhuǎn)

? ? decisionHandler(WKNavigationResponsePolicyAllow);

? ? //不允許跳轉(zhuǎn)

? ? //decisionHandler(WKNavigationResponsePolicyCancel);

}

// 在發(fā)送請(qǐng)求之前,決定是否跳轉(zhuǎn)

- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler{

? ? DDLog(@"%@",navigationAction.request.URL.absoluteString);

? ? //允許跳轉(zhuǎn)

? ? decisionHandler(WKNavigationActionPolicyAllow);

? ? //不允許跳轉(zhuǎn)

? ? //decisionHandler(WKNavigationActionPolicyCancel);

}

#pragma mark - WKScriptMessageHandler

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

? ? NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);

//注冊(cè)多個(gè)方法后,可以通過(guò)message.name區(qū)分,h5可以通過(guò)message.body返回傳值給原生

? ? WantToMentionVC *vc = [[WantToMentionVC alloc] initWithTitle:@"我要提現(xiàn)" style:WYWNavBarStyleBackBtn];

? ? [[WYWBus bus] pushVC:vc animated:YES];

}

//這個(gè)方法可以處理同步數(shù)據(jù)參數(shù),js通過(guò)調(diào)用window.prompt(text,defaultText),OC收到消息后馬上傳參給js,這個(gè)過(guò)程是同步觸發(fā)的

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{

? ? NSLog(@"%@---%@",prompt,defaultText);

? ? completionHandler(@"xxxxxxx");//這里就是要返回給JS的返回值

}

-(UIProgressView*)progressView

{

? ? if (!_progressView) {

? ? ? ? _progressView =[[UIProgressView alloc] initWithFrame:CGRectMake(0,0, [[UIScreen mainScreen] bounds].size.width, 1)];

? ? ? ? _progressView.backgroundColor = [UIColor whiteColor];

? ? ? ? _progressView.progressTintColor= [UIColor redColor];//設(shè)置已過(guò)進(jìn)度部分的顏色

? ? ? ? _progressView.trackTintColor= [UIColor lightGrayColor];//設(shè)置未過(guò)進(jìn)度部分的顏色

? ? ? ? //設(shè)置進(jìn)度條的高度,下面這句代碼表示進(jìn)度條的寬度變?yōu)樵瓉?lái)的1倍,高度變?yōu)樵瓉?lái)的1.5倍.

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

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

? ? }

? ? return _progressView;

}

//注冊(cè)方法后需要銷毀

-(void)dealloc

{

? ? [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

? ? [self.userContentController removeScriptMessageHandlerForName:@"jumpToCashVC"];

}

2、參考如下文章:

1、http://blog.csdn.net/one_person_one_life/article/details/78491899

2、http://blog.csdn.net/one_person_one_life/article/details/78563205

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

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

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