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

#import <WebKit/WebKit.h>

签协议 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.length;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<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([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);

    }

}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值