iOS 扫描相册图片二维码

级别:★★☆☆☆
标签:「iOS CIDetector」「CIQRCodeFeature」「识别相册图片」
作者: Xs·H
审校: QiShare团队


接上篇 iOS 扫描二维码/条形码,本文补充介绍扫描相册图片上二维码的实现方式。先看看QiQRCode中的示例效果:

iOS 扫描相册图片上二维码效果

iOS 8之后,可以结合CIDetector使用CIQRCodeFeature实现扫描相册图片上二维码的功能。具体实现过程如下:

1、遵守协议
@interface QiCodeManager () 
2、打开相册
- (void)presentPhotoLibraryWithRooter:(UIViewController *)rooter callback:(nonnull void (^)(NSString * _Nonnull))callback {
    _callback = callback;
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    [rooter presentViewController:imagePicker animated:YES completion:nil];
}
3、实现代理
// UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *pickedImage = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
    CIImage *detectImage = [CIImage imageWithData:UIImagePNGRepresentation(pickedImage)];
    
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    CIQRCodeFeature *feature = (CIQRCodeFeature *)[detector featuresInImage:detectImage options:nil].firstObject;
    
    [picker dismissViewControllerAnimated:YES completion:^{
        if (feature.messageString) {
            [self handleCodeString:feature.messageString];
        }
    }];
}
4、透传给业务
- (void)handleCodeString:(NSString *)codeString {
    
    if (_autoStop) {
        [self stopScanning];
    }
    if (_callback) {
        _callback(codeString);
    }
}
5、业务调用方式
// 创建“相册”按钮
UIBarButtonItem *photoItem = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(photo:)];

self.navigationItem.rightBarButtonItem = photoItem;
// 实现“相册”按钮方法
- (void)photo:(id)sender {
    
    __weak typeof(self) weakSelf = self;
    [_codeManager presentPhotoLibraryWithRooter:self callback:^(NSString * _Nonnull code) {
        [weakSelf performSegueWithIdentifier:@"showCodeGeneration" sender:code];
    }];
}

上述代码中的核心步骤是第3步—实现代理。
我们通过UIImagePickerController拿到image后,使用CIDetectorCIQRCodeFeature读取image上的信息,最终得到的feature.messageString就是二维码的字符串信息。


示例源码QiQRCode可从GitHub的QiShare开源库中获取。


推荐文章:
iOS 扫描二维码/条形码
iOS 了解Xcode Bitcode
iOS 重绘之drawRect
iOS 编写高质量Objective-C代码(八)

你可能感兴趣的:(iOS 扫描相册图片二维码)