級(jí)別:★★☆☆☆
標(biāo)簽:「iOS CIDetector」「CIQRCodeFeature」「識(shí)別相冊(cè)圖片」
作者: Xs·H
審校: QiShare團(tuán)隊(duì)
接上篇 iOS 掃描二維碼/條形碼,本文補(bǔ)充介紹掃描相冊(cè)圖片上二維碼的實(shí)現(xiàn)方式。先看看QiQRCode中的示例效果:

iOS 掃描相冊(cè)圖片上二維碼效果
iOS 8之后,可以結(jié)合CIDetector使用CIQRCodeFeature實(shí)現(xiàn)掃描相冊(cè)圖片上二維碼的功能。具體實(shí)現(xiàn)過程如下:
1、遵守協(xié)議
@interface QiCodeManager () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
2、打開相冊(cè)
- (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、實(shí)現(xiàn)代理
// UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)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、透?jìng)鹘o業(yè)務(wù)
- (void)handleCodeString:(NSString *)codeString {
if (_autoStop) {
[self stopScanning];
}
if (_callback) {
_callback(codeString);
}
}
5、業(yè)務(wù)調(diào)用方式
// 創(chuàng)建“相冊(cè)”按鈕
UIBarButtonItem *photoItem = [[UIBarButtonItem alloc] initWithTitle:@"相冊(cè)" style:UIBarButtonItemStylePlain target:self action:@selector(photo:)];
self.navigationItem.rightBarButtonItem = photoItem;
// 實(shí)現(xiàn)“相冊(cè)”按鈕方法
- (void)photo:(id)sender {
__weak typeof(self) weakSelf = self;
[_codeManager presentPhotoLibraryWithRooter:self callback:^(NSString * _Nonnull code) {
[weakSelf performSegueWithIdentifier:@"showCodeGeneration" sender:code];
}];
}
上述代碼中的核心步驟是第3步—實(shí)現(xiàn)代理。
我們通過UIImagePickerController拿到image后,使用CIDetector和CIQRCodeFeature讀取image上的信息,最終得到的feature.messageString就是二維碼的字符串信息。
示例源碼QiQRCode可從GitHub的QiShare開源庫中獲取。
推薦文章:
iOS 掃描二維碼/條形碼
iOS 了解Xcode Bitcode
iOS 重繪之drawRect
iOS 編寫高質(zhì)量Objective-C代碼(八)