神刀安全网

iOS从系统相册中识别二维码

现在的app对二维码的使用越来越频繁了,几乎每个App都有这个功能,而在iOS8之前想要识别系统相册中的二维码,只能使用第三方,iOS8之后系统加入的原生识别二维码的方式,很简单

需要先声明代理方法

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
UIImagePickerController *imagrPicker = [[UIImagePickerController alloc]init];         imagrPicker.delegate = self;         imagrPicker.allowsEditing = YES;         //将来源设置为相册         imagrPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;          [self presentViewController:imagrPicker animated:YES completion:nil];

代理方法

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{     //获取选中的照片     UIImage *image = info[UIImagePickerControllerEditedImage];      if (!image) {         image = info[UIImagePickerControllerOriginalImage];     }     //初始化  将类型设置为二维码     CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:nil];      [picker dismissViewControllerAnimated:YES completion:^{         //设置数组,放置识别完之后的数据         NSArray *features = [detector featuresInImage:[CIImage imageWithData:UIImagePNGRepresentation(image)]];          //判断是否有数据(即是否是二维码)         if (features.count >= 1) {             //取第一个元素就是二维码所存放的文本信息             CIQRCodeFeature *feature = features[0];             NSString *scannedResult = feature.messageString;             //通过对话框的形式呈现             [self alertControllerMessage:scannedResult];         }else{             [self alertControllerMessage:@"这不是一个二维码"];         }     }]; }  //由于要写两次,所以就封装了一个方法 -(void)alertControllerMessage:(NSString *)message{     UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];     UIAlertAction *action = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {     }];     [alert addAction:action];     [self presentViewController:alert animated:YES completion:nil]; }

CIDetector同时也可以做人脸识别,有兴趣的可以去研究下。

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » iOS从系统相册中识别二维码

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址