美文网首页
iOS长按识别二维码

iOS长按识别二维码

作者: 倪大头 | 来源:发表于2019-10-25 11:58 被阅读0次

给二维码图片添加长按手势:

UILongPressGestureRecognizer *QrCodeTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(qrCodeLongPress:)];
self.qrcodeImage.userInteractionEnabled = YES;
[self.qrcodeImage addGestureRecognizer:QrCodeTap];

长按手势响应方法:
CIQRCodeFeature对象就是二维码包含的内容

- (void)qrCodeLongPress:(UILongPressGestureRecognizer *)pressSender {
    if (pressSender.state != UIGestureRecognizerStateBegan) {
        return;//长按手势只会响应一次
    }
    
    UIImageView *imgV = (UIImageView *)pressSender.view;
    
    //创建上下文
    CIContext *context = [[CIContext alloc] init];
    //创建一个探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    //直接开始识别图片,获取图片特征
    CIImage *imageCI = [[CIImage alloc] initWithImage:imgV.image];
    NSArray *features = [detector featuresInImage:imageCI];
    CIQRCodeFeature *codef = (CIQRCodeFeature *)features.firstObject;
        
    //弹出选项列表
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"保存到相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImageWriteToSavedPhotosAlbum(imgV.image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
    }];
    UIAlertAction *identifyAction = [UIAlertAction actionWithTitle:@"识别二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"%@", codef.messageString);
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
    }];
    [alert addAction:saveAction];
    [alert addAction:identifyAction];
    [alert addAction:cancelAction];

    [alertController presentViewController:alert animated:YES completion:nil];
}

保存到相册的回调:

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (!error) {
        [DZStatusHud showToastWithTitle:@"保存成功" complete:nil];
    }
}

相关文章

网友评论

      本文标题:iOS长按识别二维码

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