前段时间设计提了一个需求,长按web页保存图片,以为需要前段的同事添加js事件,然后回调,像这样
__weak typeof(self) weakSelf = self;
JSContext *context= [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"getShareUrl"] = ^(NSString *articleId, NSString *title, NSString *imageUrl, NSString *shareUrl, NSString *url){
//添加处理
};
但是前端的哥们说不用,直接在客户端注入js代码就行,然后发了一句代码,核心代码如下
1.添加Long手势
UILongPressGestureRecognizer *longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
longPressed.delegate = self;
[self.webView addGestureRecognizer:longPressed];
2.手势处理
- (void)longPressed:(UILongPressGestureRecognizer *)recognizer
{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [recognizer locationInView:self.webView];
NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *imageUrl = [self.webView stringByEvaluatingJavaScriptFromString:js];
if (imageUrl.length == 0) {
return;
}
NSLog(@"image url:%@",imageUrl);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
UIImage *image = [UIImage imageWithData:data];
if (image) {
_currentImage = image;
//save image or Extract QR code
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
if (_currentImage) {
UIImageWriteToSavedPhotosAlbum(_currentImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
}];
[alertController addAction:saveAction];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
}
}
3.保存图片回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error) {
NSLog(@"保存失败");
}else{
NSLog(@"保存成功");
}
}
好了,到这里了,就是这么简单。
网友评论