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

我们给WKWebView添加一个类别: category 并起名为 Images

.h

#import 

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,点击获取图片链接)