iOS webview保存图片

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

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

接着在手势响应方法里面实现相应的获取图片地址的方法,并弹出SheetView。这里需要注意的是一定要判断手势的state属性,想知道后果的同学可以注掉判断代码自己尝试一下。另外就是如果手指长按位置是非图片的话,urlToSave是一个nil值。

- (void)longPressed:(UILongPressGestureRecognizer*)recognizer
{
    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }
    
    CGPoint touchPoint = [recognizer locationInView:self.webView];
    
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];
    
    if (urlToSave.length == 0) {
        return;
    }
    
    [self showImageOptionsWithUrl:urlToSave];
}

接下来的方法是调用一个自己封装好的SheetVIew,大家完全可以跳过,列出来只是为了不破坏代码的连贯性。

- (void)showImageOptionsWithUrl:(NSString *)imageUrl
{
    RAActionCustomButton *saveBtn = [[RAActionCustomButton alloc] init];
    saveBtn.type = kRAActionCustomButtonTypeSheetWhite;
    [saveBtn setTitle:@"保存图片" forState:UIControlStateNormal];
    saveBtn.touchUpInsideBlock = ^(RAActionCustomButton *btn){
        [self saveImageToDiskWithUrl:imageUrl];
    };
    
    RAActionCustomButton *cancelBtn = [[RAActionCustomButton alloc] init];
    cancelBtn.type = kRAActionCustomButtonTypeSheetWhite;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.touchUpInsideBlock = ^(RAActionCustomButton *btn){
        
    };
    
    RAActionSheet *sheet = [[RAActionSheet alloc] init];
    sheet.actionBtns = @[ saveBtn, cancelBtn];
    [sheet show];
}

最后就是请求图片并保存到相册的方法。这里需要注意一下cachePolicy这个参数,当前选择的参数含义是只有在cache中不存在data时才从原始地址下载。在实现过程中大家可以根据实际的功能需求来选择不同的参数。

- (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) {
        [[RAProgressHUD sharedHUD] showErrorWithMessage:@"保存失败"];
    }else{
        [[RAProgressHUD sharedHUD] showSuccessWithMessage:@"保存成功"];
    }
}

代码精髓:

NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];

猜你喜欢

转载自blog.csdn.net/ios_xumin/article/details/118296200