級(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)過(guò)程如下:
1、遵守協(xié)議
@interface QiCodeManager () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
2、打開(kāi)相冊(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)代理蝗羊。
我們通過(guò)UIImagePickerController
拿到image
后,使用CIDetector
和CIQRCodeFeature
讀取image
上的信息仁锯,最終得到的feature.messageString
就是二維碼的字符串信息耀找。
示例源碼QiQRCode可從GitHub的QiShare開(kāi)源庫(kù)中獲取。
推薦文章:
iOS 掃描二維碼/條形碼
iOS 了解Xcode Bitcode
iOS 重繪之drawRect
iOS 編寫(xiě)高質(zhì)量Objective-C代碼(八)