長(zhǎng)按 UIWebView上的圖片保存到相冊(cè)
想法一:利用JS與原生交互,JS監(jiān)聽(tīng)圖片點(diǎn)擊事件踏拜,然后將圖片的url傳遞給原生的APP端态罪,原生APP將圖片保存到相冊(cè)
想法二:利用JS的api:Document.elementFromPoint()沟饥,實(shí)現(xiàn)這個(gè)功能完全可以只在APP原生端做一些代碼開(kāi)發(fā)棺亭。
想法二的具體操作:
1.給UIWebView添加長(zhǎng)按手勢(shì)
2.監(jiān)聽(tīng)手勢(shì)動(dòng)作,拿到坐標(biāo)點(diǎn)x,y
3.彈出對(duì)話框弟劲,是否保存到相冊(cè)
4.UIWebView注入JS:Document.elementFromPoint(x,y).src拿到img標(biāo)簽的src
5.拿到圖片的url祷安,生成uiimage
6.圖片保存到相冊(cè)
重點(diǎn):長(zhǎng)按手勢(shì)事件不能每次都響應(yīng),所以要想長(zhǎng)安手勢(shì)準(zhǔn)確率100%兔乞,要實(shí)現(xiàn)UIGestureRecognizerDelegate代理方法
實(shí)現(xiàn)代碼
#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]]];
//添加長(zhǎng)按手勢(shì)
UILongPressGestureRecognizer* longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressed:)];
[self.webview addGestureRecognizer:longPressGestureRecognizer];
longPressGestureRecognizer.delegate = self;
}
#pragma mark--長(zhǎng)按代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
#pragma mark-- 長(zhǎng)按事件
- (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:@"您確定的要保存圖片到相冊(cè)嗎汇鞭?" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self saveImageToAmblue:toSaveStr];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不好意思,我點(diǎn)錯(cuò)了." 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--圖片保存后回調(diào)
- (void)imageSaveToAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(id)contextInfo{
NSString* message;
if (!error) {
message = @"已經(jīng)成功保存到相冊(cè)";
}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];
}
總結(jié):這兩種想法都有一定的局限性,想法一是太過(guò)麻煩报嵌,想法二是有的時(shí)候會(huì)獲取不到圖片的URL(若想準(zhǔn)確獲得URL需和前端做一些溝通)虱咧。鑒于此,具體使用哪種方法锚国,就看你的心情了腕巡。