美文网首页
WKWebView_OC

WKWebView_OC

作者: alex_zn | 来源:发表于2018-07-19 14:34 被阅读0次

    WebKit

    设置 WKWebViewConfiguration 配置WKWebView的属性。

    self.webView = [[WKWebView alloc] initWithFrame: self.view.bounds configuration:config];
    // 通过JS与webview内容交互

    // 通过JS与webview内容交互

     config.userContentController = [[WKUserContentController alloc] init];
    
      // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
      // 我们可以在WKScriptMessageHandler代理中接收到
      
     [config.userContentController addScriptMessageHandler: self name: @"AppModel"];
    
      // 导航代理
      self.webView.navigationDelegate = self;
      // 与webview UI交互代理
      self.webView.UIDelegate = self;
      
      // 添加KVO监听
      [self.webView addObserver:self
                     forKeyPath:@"loading"
                        options:NSKeyValueObservingOptionNew
                        context:nil];
      [self.webView addObserver:self
                     forKeyPath:@"title"
                        options:NSKeyValueObservingOptionNew
                        context:nil];
      [self.webView addObserver:self
                     forKeyPath:@"estimatedProgress"
                        options:NSKeyValueObservingOptionNew
                        context:nil];
    

    pragma mark - WKScriptMessageHandler

    - (void)userContentController:(WKUserContentController *)userContentController
          didReceiveScriptMessage:(WKScriptMessage *)message {
      if ([message.name isEqualToString:@"AppModel"]) {
        // 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
        NSLog(@"%@", message.body);
      }
    }
    

    pragma mark - KVO

    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary<NSString *,id> *)change
                           context:(void *)context {
      if ([keyPath isEqualToString:@"loading"]) {
        NSLog(@"loading");
      } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
      } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"progress: %f", self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
      }
      
      // 加载完成
      if (!self.webView.loading) {
        // 手动调用JS代码
        // 每次页面完成都弹出来,大家可以在测试时再打开
        NSString *js = @"callJsAlert()";
        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
          NSLog(@"response: %@ error: %@", response, error);
          NSLog(@"call js alert by native");
        }];
        
        [UIView animateWithDuration:0.5 animations:^{
          self.progressView.alpha = 0;
        }];
      }
    }
    

    相关文章

      网友评论

          本文标题:WKWebView_OC

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