美文网首页iOS开发记录
iOS WKWebView加载HTML,点击获取图片链接

iOS WKWebView加载HTML,点击获取图片链接

作者: iOS小武哥 | 来源:发表于2019-05-17 15:14 被阅读0次
    我们给WKWebView添加一个类别: category 并起名为 Images

    .h

    #import <WebKit/WebKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface WKWebView (Images)
    
    -(void) addTapImageGesture;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    .m

    #import "WKWebView+Images.h"
    
    
    @implementation WKWebView (Images)
    
    -(void) addTapImageGesture
    {
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction:)];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.delegate = (id)self;
        [self addGestureRecognizer:tapGesture];
    }
    //这里增加手势的返回,不然会被WKWebView拦截
    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {
        return YES;
    }
    -(void) tapGestureAction:(UITapGestureRecognizer *)recognizer
    {
        //首先要获取用户点击在WKWebView 的范围点
        CGPoint touchPoint = [recognizer locationInView:self];
        NSString *imgURLJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
        //跟着注入JS 获取 异步获取结果
        [self evaluateJavaScript:imgURLJS completionHandler:^(id result, NSError * _Nullable error) {
            if (error == nil)
            {
                NSString *url = result;
                if (url.length == 0)
                {
                    return ;
                }
                else
                {
                    //如果是url 则转换成 UIImage
                    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
                    
                    NSLog(@"dddddd = %@", url);
                    
                    UIImage *clickImg = [UIImage imageWithData:imgData];
                    if (clickImg)
                    {
                        NSArray *imgArr = @[url];
                        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
                        [tempArray addObject:clickImg];
      
                    //TO对图片的操作               
    
                    }
                    
                }
            }
        }];
    }
    
    
    @end
    
    调用,在加载完成的代理方法中进行调用:
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
    {
        [self.webView addTapImageGesture];
    }
    

    相关文章

      网友评论

        本文标题:iOS WKWebView加载HTML,点击获取图片链接

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