1、例如在我们的导航栏中设置一个按钮
-(void)setupRightMenuButton{
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"相册中选" style:UIBarButtonItemStylePlain target:self action:@selector(takeQRCodeFromPic)];
}
2、初始化相册拾取器
-(void)takeQRCodeFromPic{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
controller.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
controller.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentViewController:controller animated:YES completion:NULL];
}else{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不支持访问相册,请在设置->隐私->照片中进行设置!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
}
3、实现选中照片之后的代理事件,并将图片数据进行转码扫描
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//1.获取选择的图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
//2.初始化一个监测器
CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
[picker dismissViewControllerAnimated:YES completion:^{
//监测到的结果数组
NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
if (features.count >=1) {
/**结果对象 */
CIQRCodeFeature *feature = [features objectAtIndex:0];
NSString *scannedResult = feature.messageString;
RxWebViewController* webViewController = [[RxWebViewController alloc] initWithUrl:[NSURL URLWithString:scannedResult]];
webViewController.navigationItem.hidesBackButton = YES;
[self.navigationController pushViewController:webViewController animated:YES];
}
else{
UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该图片没有包含一个二维码!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
}];
}