iOS、长按webView 保存图片

步骤:

1、创建手势

2、监听手势,获取到点击的point

3、根据webview js代码:Document.elementFromPoint(x,y).src 拿到image的src标签,并且通过stringByEvaluatingJavaScriptFromString转换为url的字符串

4、给url做非空判断,有值时 弹出提示框,然后下载图片,通过UIImageWriteToSavedPhotosAlbum保存到相册

关键代码:一、


- (void)longPress:(UILongPressGestureRecognizer*)longPressGestureRecognizer{

if(longPressGestureRecognizer.state!=UIGestureRecognizerStateBegan){

return;

}

CGPointtouchPoint = [longPressGestureRecognizerlocationInView:self.webView];

NSString*srcStr = [NSStringstringWithFormat:@"document.elementFromPoint(%f, %f).src",touchPoint.x,touchPoint.y];

NSString*saveUrl = [self.webViewstringByEvaluatingJavaScriptFromString:srcStr];

if(srcStr.length==0){

return;

}

UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"保存图片到相册"preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction*okAction = [UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {

[selfsavePhotoToPhotosAlbumWithImgUrl:saveUrl];

}];

UIAlertAction*cancelAction = [UIAlertActionactionWithTitle:@"Cancel"style:UIAlertActionStyleCancelhandler:nil];

[alertaddAction:okAction];

[alertaddAction:cancelAction];

[selfpresentViewController:alertanimated:YEScompletion:nil];

}

- (void)savePhotoToPhotosAlbumWithImgUrl:(NSString*)url {

NSURL*ImgUrl = [NSURLURLWithString:url];

NSURLSessionConfiguration*configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];

NSURLSession*session = [NSURLSessionsessionWithConfiguration:configurationdelegate:selfdelegateQueue:[NSOperationQueuenew]];

NSURLRequest*request = [NSURLRequestrequestWithURL:ImgUrlcachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30.0];

NSURLSessionDownloadTask*task = [sessiondownloadTaskWithRequest:requestcompletionHandler:^(NSURL*_Nullablelocation,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {

if(error){

return;

}

NSData*imgData = [NSDatadataWithContentsOfURL:location];

dispatch_async(dispatch_get_main_queue(), ^{

UIImage*img = [UIImageimageWithData:imgData];

UIImageWriteToSavedPhotosAlbum(img, self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

});

}];

[taskresume];

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容