長按 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需和前端做一些溝通)。鑒于此,具體使用哪種方法,就看你的心情了。