美文网首页
webview长按保存图片

webview长按保存图片

作者: dandelionYD | 来源:发表于2019-02-02 22:53 被阅读0次

导读

我们看到今日头条能够在webview里面实现长按图片,弹出框进行图片的保存操作,今天我们也来试一试。
具体的代码,可以参见:gitHub

  • 系统的方法
#import "ViewController_system.h"
#import <WebKit/WebKit.h>
@interface ViewController_system ()
@property (nonatomic,strong) WKWebView *webView;
@end

@implementation ViewController_system
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"系统长按webview图片到本地";
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"savePhoto" ofType:@"html" inDirectory:@"html"];
    [self.webView loadFileURL:[NSURL fileURLWithPath:urlStr] allowingReadAccessToURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    [self.view addSubview:self.webView];
}
@end

效果图:


SavePhoto1.png

说明:
这里只需要使用WKWebview加载就可以了 safari其实是自带的,其他的无需操作.


  • 2.自己定义
    注意点:写网页的时候,要写上viewport的移动端的属性哟,不然不好找到img标签,或者定位不准
关键步骤:
1.要将系统的webkitTouchCallout属性干掉
2.使用自己定义的长按手势来替代系统的
3.通过touch的点 来获取当前的image对象
4.弹框、保存图片

代码如下:

#import "ViewController_custom.h"
#import <WebKit/WebKit.h>
@interface ViewController_custom ()<WKNavigationDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong) WKWebView *webView;
@end

@implementation ViewController_custom
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"自定义长按webview图片到本地";
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    self.webView.navigationDelegate = self;
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"savePhoto" ofType:@"html" inDirectory:@"html"];
    [self.webView loadFileURL:[NSURL fileURLWithPath:urlStr] allowingReadAccessToURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    [self.view addSubview:self.webView];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 0.3;
    longPress.delegate = self;
    [self.webView addGestureRecognizer:longPress];
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)sender{
    if (sender.state != UIGestureRecognizerStateBegan) {
        return;
    }
    CGPoint touchPoint = [sender locationInView:self.webView];
    NSString *imgJS = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    
    [self.webView evaluateJavaScript:imgJS completionHandler:^(id _Nullable imgUrl, NSError * _Nullable error) {
        if (imgUrl) {
            UIAlertController*alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"保存图片到相册"style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
                [self savePhotoToPhotosAlbumWithImg:imgUrl];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:okAction];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

- (void)savePhotoToPhotosAlbumWithImg:(NSString *)imgUrl {
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
    UIImage *image = [UIImage imageWithData:data];
    if (!image) {
        NSLog(@"读取图片失败");
        return;
    }
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark -- <保存到相册>
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    NSLog(@"%@",msg);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {//长按手势放开
        return YES;
    }else{
        return NO;
    }
}
@end

效果图:


SavePhoto2.png

相关文章

网友评论

      本文标题:webview长按保存图片

      本文链接:https://www.haomeiwen.com/subject/iepesqtx.html