美文网首页
WKWebView的简单使用方法(包含OC和JS交互处理)

WKWebView的简单使用方法(包含OC和JS交互处理)

作者: longkingwdlsky | 来源:发表于2018-02-26 16:49 被阅读0次

因为项目需要,需要原生页面和h5交互调用,WKWebView提供了非常丰富的代理方法,参考了各位大神的详解,记录下方便以后查询。

1、使用方法,具体代码如下(需要#import <WebKit/WebKit.h>,实现代理:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler):1.1、定义

@property (nonatomic,strong) WKWebView *webView;

@property(nonatomic,strong)WKUserContentController*userContentController;

@property (nonatomic,strong) UIProgressView *progressView;

1.2、实现

//设置一些基础参数

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

//设置OC和JS交互调用方法等

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

conf.userContentController = self.userContentController;

//注册方法(当原生需要和h5互相调用的时候,需要约定调用方法,h5调用后回调),可以注册多个方法[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];

//加载网页地址

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

//添加kvo监听,加载进度值

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

//添加KVO监听

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

//加载进度值

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

// 页面开始加载时调用

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

    self.progressView.hidden = NO;

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

    [self.view bringSubviewToFront:self.progressView];

}

// 当内容开始返回时调用

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

}

// 页面加载完成之后调用

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

//加载完成后隐藏progressView

self.progressView.hidden = YES;

//加载完成web后可以传值给h5,通过如下方法

//jsStr 包含:method(参数)

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

//此处可以打印error.

}];

//h5调用的时候只需要实现这个方法,获取对应参数即可

funtion  method(参数){

}

}

// 页面加载失败时调用

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

    //加载失败同样需要隐藏progressView

    self.progressView.hidden = YES;

    [self.webView removeFromSuperview];

}

// 接收到服务器跳转请求之后调用

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

}

// 在收到响应后,决定是否跳转

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

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

    //允许跳转

    decisionHandler(WKNavigationResponsePolicyAllow);

    //不允许跳转

    //decisionHandler(WKNavigationResponsePolicyCancel);

}

// 在发送请求之前,决定是否跳转

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

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

    //允许跳转

    decisionHandler(WKNavigationActionPolicyAllow);

    //不允许跳转

    //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);

//注册多个方法后,可以通过message.name区分,h5可以通过message.body返回传值给原生

    WantToMentionVC *vc = [[WantToMentionVC alloc] initWithTitle:@"我要提现" style:WYWNavBarStyleBackBtn];

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

}

//这个方法可以处理同步数据参数,js通过调用window.prompt(text,defaultText),OC收到消息后马上传参给js,这个过程是同步触发的

- (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];//设置已过进度部分的颜色

        _progressView.trackTintColor= [UIColor lightGrayColor];//设置未过进度部分的颜色

        //设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.

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

        [self.view addSubview:_progressView];

    }

    return _progressView;

}

//注册方法后需要销毁

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

相关文章

网友评论

      本文标题:WKWebView的简单使用方法(包含OC和JS交互处理)

      本文链接:https://www.haomeiwen.com/subject/tbmyxftx.html