- (void)longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer{
if(longPressGestureRecognizer.state != UIGestureRecognizerStateBegan){
return;
}
CGPoint touchPoint = [longPressGestureRecognizer locationInView:self.webView];
NSString *srcStr = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src",touchPoint.x,touchPoint.y];
NSString *saveUrl = [self.webView stringByEvaluatingJavaScriptFromString:srcStr];
if(srcStr.length == 0){
return;
}
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存图片到相册" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefaulthandler:^(UIAlertAction * _Nonnull action) {
[self savePhotoToPhotosAlbumWithImgUrl:saveUrl];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancelhandler:nil];
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)savePhotoToPhotosAlbumWithImgUrl:(NSString *)url {
NSURL *ImgUrl = [NSURL URLWithString:url];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue new]];
NSURLRequest *request = [NSURLRequest requestWithURL:ImgUrl cachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30.0];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(error){
return;
}
NSData *imgData = [NSData dataWithContentsOfURL:location];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *img = [UIImage imageWithData:imgData];
UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
});
}];
[task resume];
}