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

#import

签协议 WKNavigationDelegate

@property (nonatomic,strong)WKWebView *newsWebView;



- (void)createView{

    self.newsWebView = [[WKWebViewalloc] init];

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

    self.newsWebView.navigationDelegate = self;

    self.newsWebView.scrollView.scrollEnabled = NO;

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

   [self.newsWebViewaddObserver:selfforKeyPath:@"scrollView.contentSize"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:@"DJWebKitContext"];

    ///

}


#pragma mark 网页开始加载

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

   

}

#pragma mark 网页加载完成

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

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

    [selfaddImgClickJS];

  

}

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

- (void)addImgClickJS {

    //添加图片点击的回调

    [self.newsWebViewevaluateJavaScript:@"function registerImageClickAction(){\

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

     for(var i=0;i

     imgs[i].customIndex = i;\

     imgs[i].οnclick=function(){\

     window.location.href=''+this.src;\

     }\

     }\

     }" completionHandler:nil];

    [self.newsWebViewevaluateJavaScript:@"registerImageClickAction();"completionHandler:nil];

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

[self.newsWebView evaluateJavaScript:@“function getImages(){
     var imgs = document.getElementsByTagName('img');
     var imgScr = '';
     for(var i=0;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([keyPathisEqualToString:@"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 ([pathisEqualToString:@"about:blank"]) {

        decisionHandler(WKNavigationActionPolicyAllow);

    }else{

        /// 图片的点击处理

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

            查看图片内容(pod "MWPhotoBrowser", :git =>'https://github.com/EvoIos/MWPhotoBrowser.git', :commit =>'de697e101195557ddca85661ebb266fd3f10776c'

            单个图片查看

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

            _photosBrowser = [[MWPhotoBrowseralloc] 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 = [[UINavigationControlleralloc] initWithRootViewController:_photosBrowser];

            _photosBrowser.navigationItem.leftBarButtonItem = [[UIBarButtonItemalloc] initWithImage:[UIImageimageNamed:@"navBack"]style:UIBarButtonItemStylePlaintarget:selfaction:@selector(PhotobackAction)];

            nan.modalTransitionStyle =UIModalTransitionStyleCrossDissolve;

            [selfpresentViewController:nananimated:YEScompletion:^{

                

            }];

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

        }elseif ([FLGPanduanToolisWebURL:path]){

            if ([pathhasPrefix:@"http://cznews.cz001.com.cn/html/wap/detail.php?pid="]) {

                FLGNewsDetailViewController *detail = [[FLGNewsDetailViewControlleralloc] init];

                detail.newsID = [pathsubstringFromIndex:51];

                [self.navigationControllerpushViewController:detailanimated:YES];

            }else{

                 pod 'TOWebViewController','~> 2.2.6'

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

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

                nan.navigationBar.translucent =NO;

                nan.navigationBar.barTintColor =baseColor;

                nan.navigationBar.barStyle =UIStatusBarStyleLightContent;

                [nan.navigationBarsetTitleTextAttributes:@{NSFontAttributeName:[UIFontfontWithName:@"Helvetica-Bold"size:19],NSForegroundColorAttributeName:[UIColorwhiteColor]}];

                nan.modalTransitionStyle =UIModalTransitionStyleCrossDissolve;

                [selfpresentViewController:nananimated:YEScompletion:^{

                    

                }];

            }

        }

        decisionHandler(WKNavigationActionPolicyCancel);

    }

}




你可能感兴趣的:(WKWebview 获取网页高度,图片点击查看,网页链接点击)