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;

    }

    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];

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值