webView a标签保存图片
<a class="open" href="../docs/doc/" download=""
title="下载" mce_href="#"><i class="fa fa-arrow-circle-down"></i></a>
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
//拦截href图片地址
NSString *url = request.URL.relativeString;
if ([url hasPrefix:@"data:"]) {
[self saveImg:url];
return NO;
}
return YES;
}
//保存图片
-(void)saveImg:(NSString *)imageUrl{
NSLog(@"image url:%@",imageUrl);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
UIImage *image = [UIImage imageWithData:data];
if (image) {
[AlertView alertTitle:@"提示" message:@"保存图片至相册" sureTitle:@"确定" sureAction:^{
[self savePhotoToAlbumWithImageUrl:imageUrl];
} cancelTitle:@"取消"];
}
}
//保存到相册
- (void)savePhotoToAlbumWithImageUrl:(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:NSURLRequestReturnCacheDataElseLoad timeoutInterval: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:), nil);
});
}];
[task resume];
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
if(error != NULL){
[AlertView alertTitle:@"保存图片失败"];
}else{
[AlertView alertTitle:@"保存图片成功"];
}
}
webView长按图片下载
//长按保存图片
- (void)longPressed:(UITapGestureRecognizer*)recognizer
{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [recognizer locationInView:self.webView];
NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *imageUrl = [self.webView stringByEvaluatingJavaScriptFromString:js];
if (imageUrl.length == 0) {
return;
}
NSLog(@"image url:%@",imageUrl);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
UIImage *image = [UIImage imageWithData:data];
if (image) {
[self saveImg: imageUrl];
//......
//save image or Extract QR code
}
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}