长按 UIWebView上的图片保存到相册
想法一:利用JS与原生交互,JS监听图片点击事件,然后将图片的url传递给原生的APP端,原生APP将图片保存到相册
想法二:利用JS的api:Document.elementFromPoint(),实现这个功能完全可以只在APP原生端做一些代码开发。
想法二的具体操作:
1.给UIWebView添加长按手势
2.监听手势动作,拿到坐标点x,y
3.弹出对话框,是否保存到相册
4.UIWebView注入JS:Document.elementFromPoint(x,y).src拿到img标签的src
5.拿到图片的url,生成uiimage
6.图片保存到相册
重点:长按手势事件不能每次都响应,所以要想长安手势准确率100%,要实现UIGestureRecognizerDelegate代理方法
实现代码
#import "ImageSaveViewController.h"
@interface ImageSaveViewController ()
@property (strong, nonatomic) UIWebView* webview;
@end
@implementation ImageSaveViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.webview = [[UIWebView alloc]init];
[self.view addSubview:self.webview];
self.webview.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64);
NSString* url = [NSString stringWithFormat:@"https://www.baidu.com"];
[self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
//添加长按手势
UILongPressGestureRecognizer* longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressed:)];
[self.webview addGestureRecognizer:longPressGestureRecognizer];
longPressGestureRecognizer.delegate = self;
}
#pragma mark--长按代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
#pragma mark-- 长按事件
- (void)longPressed:(UILongPressGestureRecognizer *)recognizer{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [recognizer locationInView:self.webview];
NSString* imageURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSLog(@"%@",imageURL);
NSString* toSaveStr = [self.webview stringByEvaluatingJavaScriptFromString:imageURL];
NSLog(@"%@",toSaveStr);
if (toSaveStr.length == 0) {
return;
}
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"尊敬的客户" message:@"您确定的要保存图片到相册吗?" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self saveImageToAmblue:toSaveStr];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不好意思,我点错了." style:UIAlertActionStyleDefault handler:nil];
[alertVC addAction:okAction];
[alertVC addAction:cancelAction];
[self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark---保存图片
- (void)saveImageToAmblue:(NSString *)saveToURL{
NSURL* URL = [NSURL URLWithString:saveToURL];
NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue new]];
NSURLRequest* request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
NSURLSessionDownloadTask* downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
return ;
}
NSData* data = [NSData dataWithContentsOfURL:location];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage* iamge = [UIImage imageWithData:data];
UIImageWriteToSavedPhotosAlbum(iamge, session, @selector(imageSaveToAlbum: didFinishSavingWithError: contextInfo:), NULL);
});
}];
[downloadTask resume];
}
#pragma mark--图片保存后回调
- (void)imageSaveToAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(id)contextInfo{
NSString* message;
if (!error) {
message = @"已经成功保存到相册";
}else{
message = [error description];
}
UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* OKSection = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
[alertController addAction:OKSection];
[self presentViewController:alertController animated:YES completion:nil];
}
总结:这两种想法都有一定的局限性,想法一是太过麻烦,想法二是有的时候会获取不到图片的URL(若想准确获得URL需和前端做一些沟通)。鉴于此,具体使用哪种方法,就看你的心情了。