接力上一篇扫描本地二维码的简文. 这次为大家介绍的是本地读取二维码的基本方法, 代码少, 相对easy.
2.本地读取二维码
注意事项:
(1)iOS8之后, 苹果才提供本地识别二维码条形码等功能, iOS8之前无法使用CIDetector类. (2)只有系统生成的二维码才能扫描出来 !!! 这点应特别留意
大概流程:
(1)判断用户的操作权限以及系统版本
(2)跳转到手机相册
(3)实现代理<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
(4)读取图片内容处理
上代码 上代码 -_-
// 判断是否有权限
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message: @"请先到系统“隐私”中打开相机权限" delegate: nil cancelButtonTitle: @"知道了" otherButtonTitles: nil];
alert.delegate = self;
alert.alertViewStyle = UIAlertActionStyleDefault;
[alert show];
return; }
// 判断 iOS 版本是否超过8.0, 低于该版本无法从本地选取图片读取
NSString *deviceVersion = [[UIDevice currentDevice] systemVersion];
if ([deviceVersion floatValue] < 8.0) {
// 低于该版本, 提示用户处理方法
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"用户提示" message: @"抱歉, 你当前的系统版本小于8.0, 不能从本地扫描二维码, 请升级系统版本或者使用当前摄像头扫描" delegate: nil cancelButtonTitle: @"知道了" otherButtonTitles: nil];
alert.delegate = self;
alert.alertViewStyle = UIAlertViewStyleDefault;
[alert show]; }
else {
// 从相册中选择二维码图片
if ( [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary] ) {
UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
pickerVC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
pickerVC.delegate = self;
// 转场动画
pickerVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.navigationController pushViewController: pickerVC animated: YES]; } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message: @"未知原因, 打开相册失败" delegate: nil cancelButtonTitle: @"知道了" otherButtonTitles: nil];
alert.delegate = self;
alert.alertViewStyle = UIAlertActionStyleDefault;
[alert show];
return ; } }
实现代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
// 使用 CIDetector 处理 图片
UIImage *QRCodeImage = info[UIImagePickerControllerOriginalImage];
CIDetector *detector = [CIDetector detectorOfType: CIDetectorTypeQRCode context: nil options: @{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
[picker dismissViewControllerAnimated: YES completion:^{
// 获取结果集(二维码的所有信息都包含在结果集中, 跟扫描出来的二维码的信息是一致的)
NSArray *result = [detector featuresInImage: [CIImage imageWithCGImage: QRCodeImage.CGImage]];
if (result.count > 0) {
// 结果集元素
CIQRCodeFeature *feature = [result objectAtIndex: 0];
NSString *obj = feature.messageString;
// 二维码信息处理
NSLog(@"obj: %@", obj); } }]; }
github 下载地址: https://github.com/ZenKingLen/KLAboutQRCodeDemo