//添加长按手势
UILongPressGestureRecognizer *lp = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
//长按时长 1秒
lp.minimumPressDuration = 1;
lp.delegate = self;
[self.WKView addGestureRecognizer:lp];
#pragma mark - 保存图片
- (void)handleLongPress:(UILongPressGestureRecognizer *)sender{
if (sender.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [sender locationInView:self.WKView];
CGFloat ptX, ptY;
ptX = touchPoint.x;
ptY = touchPoint.y;
[self.WKView evaluateJavaScript:[NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSString * tagName = response;
if ([tagName isEqualToString:@"IMG"]) {
[self->_WKView evaluateJavaScript:[NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSString * imgUrl = response;
if (imgUrl) {
UIImage *img = [self downloadImage:imgUrl];
if (!img) {
return;
}
UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
}];
UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
}];
[alert addAction:cancelAction];
[alert addAction:saveAction];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}];
}
- (UIImage *)downloadImage:(NSString *)urlString {
NSURL *url = [NSURL URLWithString: urlString];
UIImage *img;
NSData *data = [NSData dataWithContentsOfURL:url];
img = [UIImage imageWithData:data];
if (!img) {
//MBPSHOW(@"读取图片失败");
NSLog(@"读取图片失败");
return nil;
}
return img;
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error != NULL) {
//MBPSHOW(@"图片保存失败");
NSLog(@"图片保存失败");
}else
{
// MBPSHOW(@"图片保存成功");
NSLog(@"图片保存成功");
}
}
网友评论