我們給WKWebView添加一個(gè)類別: 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];
}
//這里增加手勢(shì)的返回,不然會(huì)被WKWebView攔截
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
-(void) tapGestureAction:(UITapGestureRecognizer *)recognizer
{
//首先要獲取用戶點(diǎn)擊在WKWebView 的范圍點(diǎn)
CGPoint touchPoint = [recognizer locationInView:self];
NSString *imgURLJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
//跟著注入JS 獲取 異步獲取結(jié)果
[self evaluateJavaScript:imgURLJS completionHandler:^(id result, NSError * _Nullable error) {
if (error == nil)
{
NSString *url = result;
if (url.length == 0)
{
return ;
}
else
{
//如果是url 則轉(zhuǎn)換成 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對(duì)圖片的操作
}
}
}
}];
}
@end
調(diào)用,在加載完成的代理方法中進(jìn)行調(diào)用:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
[self.webView addTapImageGesture];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者