UIWebView 实现长按保存图片功能

拿到需求之后分析了一下,其实主要功能点就是如何才能通过手指按压位置获取到相应的图片资源。

首先是给UiWebView加一个长按手势 :

UILongPressGestureRecognizer* longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
longPressed.delegate = self;
[self.webView addGestureRecognizer:longPressed];

响应方法:

- (void)longPressed:(UILongPressGestureRecognizer*)recognizer
{

    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }

    CGPoint touchPoint = [recognizer locationInView:self.webView];
    NSString *jsForTagName = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", touchPoint.x, touchPoint.y];
    NSString * tagName = [self.webView stringByEvaluatingJavaScriptFromString:jsForTagName];
    if (![tagName isEqualToString:@"img"] && ![tagName isEqualToString:@"IMG"]) {
        return;
    }
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    self.urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];

    if (self.urlToSave.length == 0) {
        return;
    }

    [self showImageOptionsWithUrl:self.urlToSave];
}

弹窗提示:

- (void)showImageOptionsWithUrl:(NSString *)imageUrl
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:@"保存图片"
                                  otherButtonTitles: nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self saveImageToDiskWithUrl:self.urlToSave];
    }
}

// 执行保存操作
- (void)saveImageToDiskWithUrl:(NSString *)imageUrl
{
    NSURL *url = [NSURL URLWithString:imageUrl];
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self  delegateQueue:[NSOperationQueue new]];
    NSURLRequest *imgRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];

    NSURLSessionDownloadTask  *task = [session downloadTaskWithRequest:imgRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            return ;
        }

        NSData * imageData = [NSData dataWithContentsOfURL:location];
        dispatch_async(dispatch_get_main_queue(), ^{

            UIImage * image = [UIImage imageWithData:imageData];

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

    [task resume];
}

// 监测是否保存成功
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        NSLog(@"保存fail");
        [UMComShowToast fetchFailWithNoticeMessage:@"保存失败"];
        //        [[RAProgressHUD sharedHUD] showErrorWithMessage:@"保存失败"];
    } else {
        NSLog(@"保存成功");
        //        [[RAProgressHUD sharedHUD] showSuccessWithMessage:@"保存成功"];
        [UMComShowToast fetchFailWithNoticeMessage:@"保存成功"];
    }
}