UIWebView長按保存圖片

前段時間設計提了一個需求,長按web頁保存圖片,以為需要前段的同事添加js事件,然后回調,像這樣

__weak typeof(self) weakSelf = self;
    JSContext *context= [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"getShareUrl"] = ^(NSString *articleId, NSString *title, NSString *imageUrl, NSString *shareUrl, NSString *url){
       //添加處理
    };

但是前端的哥們說不用,直接在客戶端注入js代碼就行,然后發了一句代碼,核心代碼如下
1.添加Long手勢

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

2.手勢處理

- (void)longPressed:(UILongPressGestureRecognizer *)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) {
        _currentImage = image;
        //save image or Extract QR code
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"保存圖片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            if (_currentImage) {
                UIImageWriteToSavedPhotosAlbum(_currentImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            }
        }];
        [alertController addAction:saveAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

3.保存圖片回調

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        NSLog(@"保存失敗");
    }else{
        NSLog(@"保存成功");
    }
}

好了,到這里了,就是這么簡單。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容