WebView 长按识别二维码和点击查看大图

本地识别二维码

文末有 Demo 地址, 挺简单的, 不想看字可以直接看 demo

CIDetecor

1, 首先要识别本地二维码, webView 基本只是几条 js 语句的问题.
创建 QRCodeDetector 类:

#import "YNQRCodeDetector.h"

@implementation YNQRCodeDetector

+ (CIQRCodeFeature *)yn_detectQRCodeWithImage:(UIImage *)image {
    // 1. 创建上下文
    CIContext *context = [[CIContext alloc] init];
    
    // 2. 创建探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    
    // 3. 识别图片获取图片特征
    CIImage *imageCI = [[CIImage alloc] initWithImage:image];
    NSArray<CIFeature *> *features = [detector featuresInImage:imageCI];
    CIQRCodeFeature *codeF = (CIQRCodeFeature *)features.firstObject;
    
    return codeF;
}

@end

2, 在本地 imageView 中添加手势, 处理二维码识别的链接, 有二维码显示保存和识别, 没有只显示保存

- (void)imageLongPress {
    
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    CIQRCodeFeature *codeF = [YNQRCodeDetector yn_detectQRCodeWithImage:self.imageView.image];
    
    [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [ac addAction:[UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self savePicture];
    }]];
    
    if (codeF.messageString) {
        
        [ac addAction:[UIAlertAction actionWithTitle:@"识别二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 内置浏览器打开网页
            SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:codeF.messageString]];
            [self presentViewController:safariVC animated:YES completion:nil];
        }]];
    }
    
    [self presentViewController:ac animated:YES completion:nil];
}

3, 保存图片没什么好说的, 记得 iOS 10 以后手动开启相册权限

- (void)savePicture {
    if (self.imageView.image == nil) {
//        [SVProgressHUD showErrorWithStatus:@"图片还未加载"];
    } else {
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    
    if (error) {
        
//        [SVProgressHUD showErrorWithStatus:@"保存失败"];
        
    } else {
        
//        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
    
}

WebView上的一些处理

WebView添加长按手势

因为项目需求, 需要改的地方太多了, 我直接写在自定义 WebView 里面了, 直接替换 webView 即可. 因为公司需求的 web 没有过于复杂的功能, 直接写在自定义 webView 就行.

自定义 webView 添加长按手势:

- (instancetype)init {
    self = [super init];
    if (self) {
        [self basicConfigure];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self basicConfigure];
    }
    return self;
}

- (void)basicConfigure {
    self.delegate = self;
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressWebPic:)];
    longPress.delegate = self;
    [self addGestureRecognizer:longPress];
}

- (void)longPressWebPic:(UILongPressGestureRecognizer *)recognizer {
    
    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }
    
    // 获取点击区域坐标, 通过坐标得到图片
    CGPoint touchPoint = [recognizer locationInView:self];
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    NSString *urlToSave = [self stringByEvaluatingJavaScriptFromString:imgURL];
    
    if (urlToSave.length == 0) {
        return;
    }
    
//    ENLog(@"%@", urlToSave);
    
    [self imageWithUrl:urlToSave];
    
}

下载图片

// 因为做了个 demo 不想引用三方, 可以用 sdImageDownloader 替代
- (void)imageWithUrl:(NSString *)imageUrl {

// 在子线程中下载图片, 不在子线程中下载图片会造成主线程阻塞, 导致 alertController 需要很久时间才弹出    
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        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];
            
            // 在主线程中配置 UI 显示相关操作
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIImage *image = [UIImage imageWithData:imageData];
                
                UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                
                CIQRCodeFeature *codeF = [YNQRCodeDetector yn_detectQRCodeWithImage:image];
                
                [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                
                [ac addAction:[UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self savePicture:image];
                }]];
                
                if (codeF.messageString) {
                    
                    [ac addAction:[UIAlertAction actionWithTitle:@"识别二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:codeF.messageString]];
                        [[self currentViewController] presentViewController:safariVC animated:YES completion:nil];
                    }]];
                    
                }
                // 直接用 webView 模态出控制器
                [[self currentViewController] presentViewController:ac animated:YES completion:nil];
            });   
        }];
        
        [task resume];
    });
}

获取最上层控制器

- (UIViewController *)currentViewController {
    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;
        
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

- (UINavigationController *)currentNavigationController {
    return [self currentViewController].navigationController;
}

处理 WebView 代理方法 (js 处理)

- (void)webViewDidFinishLoad:(UIWebView *)webView {

// 屏蔽网页自带操作
    [self stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    NSString * jsCallBack = @"window.getSelection().removeAllRanges();";
    [webView stringByEvaluatingJavaScriptFromString:jsCallBack];
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    // 获取图片链接
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    // 将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    
    // 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        ENLog(@"------%@", imageUrl);
        // 点击网页图片查看大图
        ShowBigPicController *sb = [[ShowBigPicController alloc] init];
        sb.imageURL = imageUrl;
        [[self currentViewController] presentViewController:sb animated:NO completion:nil];
        
        return NO;
    }
    return YES;
}

Demo 地址

YNQRCodeWebView

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,952评论 4 60
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,142评论 25 707
  • 这是短书集第169篇文章,是讲述爱的一种 解说词:自从打开《人类简史》这本书之后,我才发现“观测者的视角”这一命题...
    Andylee阅读 392评论 0 0
  • 当第一丝光明照亮远方的路,踏上征程去往远方。不知路有多远,只有赶路的人在前方。相互交知的道路互相重叠,命中的相...
    万变妖阅读 152评论 0 0
  • css初体验,内容包含以下几点: 标签选择器(下); CSS三大特性; div和span; 块级元素、行内元素、行...
    敲出天下阅读 882评论 0 1