美文网首页iOS
iOS WKWebView添加长按手势保存H5图片

iOS WKWebView添加长按手势保存H5图片

作者: Long_iOS | 来源:发表于2022-07-13 15:00 被阅读0次
//添加长按手势
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(@"图片保存成功");
    }
}

相关文章

网友评论

    本文标题:iOS WKWebView添加长按手势保存H5图片

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