WKWebView 获取网页高度,图片点击查看,网页链接点击

#import <WebKit/WebKit.h>

签协议 WKNavigationDelegate

@property (nonatomic, strong) WKWebView *newsWebView;

  • (void)createView{

    self.newsWebView = [[WKWebView alloc] init];

    self.newsWebView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);

    self.newsWebView.navigationDelegate = self;

    self.newsWebView.scrollView.scrollEnabled = NO;

    /// 添加监听网页高度,,将网页作为tableview的头视图

    [self.newsWebView addObserver:self forKeyPath:@”scrollView.contentSize”options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@”DJWebKitContext”];

    }

#pragma mark 网页开始加载

  • (void)webView:(WKWebView )webView didStartProvisionalNavigation:(WKNavigation)navigation{

}

#pragma mark 网页加载完成

  • (void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation)navigation{

    /// 给网页中的图片添加点击方法

    [self addImgClickJS];

}

/// 给网页中的图片添加点击方法

  • (void)addImgClickJS {

    //添加图片点击的回调

    [self.newsWebView evaluateJavaScript:@”function registerImageClickAction(){

    var imgs = document.getElementsByTagName(‘img’);

    for(var i=0;i<imgs.length;i++){

    imgs[i].customIndex = i;

    imgs[i].onclick=function(){

    window.location.href=’’+this.src;

    }

    }

    }” completionHandler:nil];

    [self.newsWebView evaluateJavaScript:@”registerImageClickAction();”completionHandler:nil];

///// 所有图片点击滑动查看添加以下代码 单图片查看不需要添加

[self.newsWebView evaluateJavaScript:@“function getImages(){

 var imgs = document.getElementsByTagName('img');

 var imgScr = '';

 for(var i=0;i<imgs.length;i++){

 if (i == 0){

 imgScr = imgs[i].src;

 } else {

 imgScr = imgScr +'***'+ imgs[i].src;

 }

 };

 return imgScr;

 };” completionHandler:nil];//注入js方法

[self.newsWebView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {

    if (!error) {

        self.imagesArr = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:

        nil;

    }

}];

}

#pragma mark 监听网页的内容高度

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

if (!self.newsWebView.isLoading) {

    if([keyPath isEqualToString:@"scrollView.contentSize"]){

        self.newsWebView.frame = CGRectMake(0, 0, WIDTH,self.newsWebView.scrollView.contentSize.height);

        self.newsTableView.tableHeaderView = self.newsWebView;

    }

}

}

#pragma mark 页面加载失败时调用

  • (void)webView:(WKWebView )webView didFailProvisionalNavigation:(WKNavigation)navigation {

}

#pragma mark 在发送请求之前,决定是否跳转

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

    NSString *path = [navigationAction.request.URL.absoluteStringstringByRemovingPercentEncoding];

// NSLog(@”-=-=-==-=%@”,path);

/// 主页面加载

if ([path isEqualToString:@"about:blank"]) {

    decisionHandler(WKNavigationActionPolicyAllow);

}else{

    /// 图片的点击处理

    if ([path hasSuffix:@".png"]||[path hasSuffix:@".jpg"]||[pathhasSuffix:@".jpeg"]) {

        //// 查看图片内容(pod "MWPhotoBrowser", :[Git](http://lib.csdn.net/base/git "Git知识库") =>'<https://github.com/EvoIos/MWPhotoBrowser>.[git](http://lib.csdn.net/base/git "Git知识库")', :commit =>'de697e101195557ddca85661ebb266fd3f10776c’

//// 单个图片查看

MWPhoto *photo = [[MWPhoto alloc] initWithURL[NSURLURLWithString:path]];

_photosBrowser = [[MWPhotoBrowser alloc] initWithPhotos:@[photo]];

/// 所有图片滑动查看用下面一段替换上面两行

NSMutableArray *photoarr = [NSMutableArray array];

        for (NSString *url in self.imagesArr) {

            MWPhoto *photo = [[MWPhoto alloc] initWithURL:[NSURL URLWithString:url]];

            [photoarr addObject:photo];

        }

        _photosBrowser = [[MWPhotoBrowser alloc] initWithPhotos:photoarr];

        if ([self.imagesArr containsObject:path]) {

            NSInteger k = [self.imagesArr indexOfObject:path];

            [_photosBrowser setCurrentPhotoIndex:k];

        }else{

            [_photosBrowser setCurrentPhotoIndex:0];

        }

UINavigationController *nan = [[UINavigationController alloc] initWithRootViewController:_photosBrowser];

_photosBrowser.navigationItem.leftBarButtonItem = [[UIBarButtonItemalloc] initWithImage:[UIImage imageNamed:@”navBack”]style:UIBarButtonItemStylePlain target:self action:@selector(PhotobackAction)];

        nan.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

        [self presentViewController:nan animated:YES completion:^{

        }];

        /// 其他网页连接的处理

    }else if ([FLGPanduanTool isWebURL:path]){

        if ([path hasPrefix:@"<http://cznews.cz001.com.cn/html/wap/detail>.[PHP](http://lib.csdn.net/base/php "PHP知识库")?pid="]) {

            FLGNewsDetailViewController *detail = [[FLGNewsDetailViewControlleralloc] init];

            detail.newsID = [path substringFromIndex:51];

            [self.navigationController pushViewController:detail animated:YES];

        }else{

            //// pod 'TOWebViewController', '~> 2.2.6'

            TOWebViewController *webVC = [[TOWebViewController alloc] initWithURLString:path];

            UINavigationController *nan = [[UINavigationController alloc] initWithRootViewController:webVC];

            nan.navigationBar.translucent = NO;

            nan.navigationBar.barTintColor = baseColor;

            nan.navigationBar.barStyle = UIStatusBarStyleLightContent;

            [nan.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];

            nan.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

            [self presentViewController:nan animated:YES completion:^{

            }];

        }

    }

    decisionHandler(WKNavigationActionPolicyCancel);

}

}

web的图片点击

//这个是网页加载完成,导航的变化

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

[self addImgClickJS];

}

  • (void)addImgClickJS {

    //获取所以的图片标签

    [self.wkWebView evaluateJavaScript:@”function getImages(){

       var imgs = document.getElementsByTagName('img');
    
       var imgScr = '';
    
       for(var i=0;i<imgs.length;i++){
    
           if (i == 0){
    
              imgScr = imgs[i].src;
    
           } else {
    
              imgScr = imgScr +'***'+ imgs[i].src;
    
           }
    
       };
    
       return imgScr;

    };” completionHandler:nil];//注入js方法

    __weak typeof(self)weakSelf = self;

    [self.wkWebView evaluateJavaScript:@”getImages()” completionHandler:^(id _Nullable result, NSError * _Nullable error) {

      if (!error) {
    
          NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil;
    
          NSLog(@"urlArray = %@",urlArray);
    
          weakSelf.imageUrlArr = urlArray;
    
      } else {
    
          weakSelf.imageUrlArr = nil;
    
      }

    }];

    //添加图片点击的回调

    [self.wkWebView evaluateJavaScript:@”function registerImageClickAction(){

       var imgs = document.getElementsByTagName('img');
    
       for(var i=0;i<imgs.length;i++){
    
           imgs[i].customIndex = i;
    
           imgs[i].onclick=function(){
    
              window.location.href='image-preview-index:'+this.customIndex;
    
           }
    
       }

    }” completionHandler:nil];

    [self.wkWebView evaluateJavaScript:@”registerImageClickAction();” completionHandler:nil];

}

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

    // 类似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:

    //预览图片

    NSURL * url = navigationAction.request.URL;

    if ([url.scheme isEqualToString:@”image-preview-index”]) {

      //图片点击回调
    
      NSInteger index = [[url.absoluteString substringFromIndex:[@"image-preview-index:" length]] integerValue];
    
      NSString * imgPath = self.imageUrlArr.count > index?self.imageUrlArr[index]:nil;
    
      NSLog(@"imgPath = %@",imgPath);
    
      decisionHandler(WKNavigationActionPolicyCancel);

    } else {

      decisionHandler(WKNavigationActionPolicyAllow);

    }

}

当计算高度使用监听方法出现问题的时候(plus 机型上拉记载出现抖动) 可以换一种方法

#pragma mark 网页加载完成

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

    [self performSelector:@selector(loadHeight) withObject:self afterDelay:1];

}

一定要在1s延时之后 才能正确获取网页高度

  • (void)loadHeight{

    self.detailTableView.hidden = NO;

    CGFloat height = 0.0;

    [self.detailWebView sizeToFit];

    height = self.detailWebView.scrollView.contentSize.height;

    CGRect webFrame = self.detailWebView.frame;

    webFrame.size.height = height;

    self.detailWebView.frame = webFrame;

    self.headView.frame = CGRectMake(0, 0, WIDTH, 90FITWIDTH+height+100FITWIDTH);

    self.detailTableView.tableHeaderView = self.headView;

    [self hiddenSVProgress];

}

不用延时1s的方法

[webView evaluateJavaScript:@”document.body.scrollHeight”completionHandler:^(id _Nullable result,NSError * _Nullable error){

    CGFloat height = [result floatValue];

    self.newsWebView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, height);

    [self.delegate webViewDidFinishLoad:height cellIndex:self.indexPath];

}];
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!