美文网首页
WKWebView的使用

WKWebView的使用

作者: 浅浅_e90e | 来源:发表于2021-09-23 09:57 被阅读0次

    1、导入头文件

    #import <WebKit/WebKit.h>
    

    2、解决内存不释放,单独创建一个WKScriptMessageHandler

    // WKWebView 内存不释放的问题解决
    @interface WeakWebViewScriptMessageDelegate : NSObject<WKScriptMessageHandler>
    
    //WKScriptMessageHandler 这个协议类专门用来处理JavaScript调用原生OC的方法
    @property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;
    
    - (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
    
    @end
    @implementation WeakWebViewScriptMessageDelegate
    
    - (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
        self = [super init];
        if (self) {
            _scriptDelegate = scriptDelegate;
        }
        return self;
    }
    
    #pragma mark - WKScriptMessageHandler
    //遵循WKScriptMessageHandler协议,必须实现如下方法,然后把方法向外传递
    //通过接收JS传出消息的name进行捕捉的回调方法
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        
        if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
            [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
        }
    }
    
    @end
    

    3、控制器遵守协议<WKNavigationDelegate,WKScriptMessageHandler>
    4、声明WKWebView和网页进度指示器

        /** 当前的webview*/
        WKWebView           *webView;
        /** 网页进度条*/
        UIProgressView      *progressView;
    

    5、创建WKWebView实例对象

    - (void)createWebView {
        [webView removeFromSuperview];
        webView = nil;
        
        //创建WKWebViewConfiguration文件
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        //注册一个name为xxx的js方法(由前端开发工程师提供) 设置处理接收JS方法的对象
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"javascript给定的和原生App交互的函数名"];
        config.userContentController = wkUController;
        
        // 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        //最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果
        preference.minimumFontSize = 0;
        //设置是否支持javaScript 默认是支持的
        preference.javaScriptEnabled = YES;
        // 在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口
        preference.javaScriptCanOpenWindowsAutomatically = NO;
        config.preferences = preference;
    
        webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWith, ScreenHeight-NaviHeight) configuration:config];
        
        // 导航代理
        webView.navigationDelegate = self;
        // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
        webView.allowsBackForwardNavigationGestures = NO;
        webView.backgroundColor = [UIColor grayColor];
        webView.scrollView.backgroundColor = [UIColor grayColor];
        for (UIScrollView *view in webView.subviews) {
            if ([view isKindOfClass:[UIScrollView class]]) {
                [view setShowsHorizontalScrollIndicator:NO];
                view.bounces = NO;
            }
        }
        [webView setOpaque:NO];
        [self.contentView addSubview:webView];
        
        //添加监测网页加载进度的观察者
        [webView addObserver:self         forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                          options:0
                          context:nil];
    }
    

    6、创建网页进度加载指示器

    - (void)createWebIndicator {
        progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, NaviHeight-2, ScreenWith, 2)];
        progressView.tintColor = [UIColor yellowColor];
        progressView.trackTintColor = [UIColor clearColor];
        [self.view addSubview:progressView];
    }
    

    7、实现WKWebView的代理方法

    ///适应HTTPs请求的代理方法
    - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential,card);
        }
    }
    #pragma mark - WKScriptMessageHandler
    /**
     * 被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来
     * 通过接收JS传出消息的name进行捕捉的回调方法
     */
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"name:%@",message.name);
        NSLog(@"body:%@",message.body);
        NSLog(@"info:%@",message.frameInfo);
        if (!message.name || ![message.name isKindOfClass:[NSString class]] || [message.name length] == 0) {
            return ;
        }
        ///获取H5页面返回的数据并转成NSDictionary类型
        NSDictionary *parameter = @{};
        if (message.body && [message.body isKindOfClass:[NSDictionary class]]) {
            parameter = (NSDictionary *)message.body;
        }
      ///根据H5函数返回的数据做相应的处理
        if ([message.name isEqualToString:@"javascript函数名"]) {
            if ([parameter objectForKey:@"javascript函数传回的数据里,给定的Key值"] && [[parameter objectForKey:@"javascript函数传回的数据里,给定的Key值"] isKindOfClass:[NSString class]]) {
               ///获取到了H5页面传回的某个key对应的value值,做相应的处理,传参或者跳转页面等等
            }
        }
    ///可以注册并接收多个JavaScript函数对象
    }
    
    
    #pragma mark- kvo 监听进度 必须实现此方法
    - (void)observeValueForKeyPath:(NSString *)keyPath
                         ofObject:(id)object
                           change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                          context:(void *)context{
        
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
            && object == webView) {
            
          NSLog(@"网页加载进度 = %f",webView.estimatedProgress);
            progressView.progress = webView.estimatedProgress;
            if (webView.estimatedProgress >= 1.0f) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    progressView.progress = 0;
                });
            }
            
        }else{
            [super observeValueForKeyPath:keyPath
                                 ofObject:object
                                   change:change
                                  context:context];
        }
    }
    
    #pragma mark -- WKNavigationDelegate
    /*
     *  WKNavigationDelegate主要处理一些跳转、加载处理操作,
     *  WKUIDelegate主要处理JS脚本,确认框,警告框等
     */
    // 页面开始加载时调用
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
        NSLog(@"页面开始加载时调用");
       ///隐藏网页加载错误视图
    }
    
    // 当内容开始返回时调用
    - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
        NSLog(@"当内容开始返回时调用");
    }
    
    // 页面加载完成之后调用
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
       NSLog(@"页面加载完成之后调用");
        [progressView setProgress:0.0f animated:NO];
    }
    
    // 页面加载失败时调用
    - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"页面加载失败时调用");
       ///显示网络加载错误视图
        [progressView setProgress:0.0f animated:NO];
    }
    
    // 提交发生错误时调用
    - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
        NSLog(@"提交发生错误时调用");
        ///显示网络加载错误视图
        [progressView setProgress:0.0f animated:NO];
    }
    
    // 接收到服务器跳转请求即服务重定向时之后调用
    - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
        NSLog(@"接收到服务器跳转请求即服务重定向时之后调用");
    }
    
    // 进程被终止时调用
    - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
        NSLog(@"进程被终止时调用");
    }
    
    /**
     *  在发送请求之前,决定是否跳转
     *  可以拦截到每次加载
     */
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
        NSLog(@"b %@",navigationAction.request.URL.absoluteString);
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    

    8、在页面注销的dealloc方法中移除加载进度观察者对象和注册的所有ScriptMessageHandler

    - (void)dealloc {
        ///移除ScriptMessageHandler
        [[webView configuration].userContentController removeScriptMessageHandlerForName:@"javascript给定的和原生App交互的函数名"];
       ///移除观察者
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    相关文章

      网友评论

          本文标题:WKWebView的使用

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