ios使用AVFoundation读取二维码的方法

2020-01-21 03:31:36丽君

然后切换到ViewController.m文件,在startStopAction:方法中添加下面代码以启用和暂停计时器:


- (IBAction)startStopAction:(id)sender
{
 if (!self.isReading) {
  ...
  [self.view bringSubviewToFront:self.scanView]; // display scanView
  self.scanView.timer.fireDate = [NSDate distantPast]; //start timer
  ...
 }
 else {
  [self stopScanning];
  self.scanView.timer.fireDate = [NSDate distantFuture]; //stop timer
  ...
 }
 
 ...
}

最后,再在viewWillAppear:的重写方法中添加下面代码:


- (void)viewWillAppear:(BOOL)animated
{
 [super viewWillAppear:animated];
 
 self.scanView.timer.fireDate = [NSDate distantFuture];
}

可以运行看下:

ios,二维码,AVFoundation

2.3.4 从图片解析二维码

从iOS 8开始,可以使用Core Image框架中的CIDetector解析图片中的二维码。在这个应用中,我们通过点击Album按钮,从相册选取二维码来解析。

在写代码之前,需要在Info.plist文件中添加NSPhotoLibraryAddUsageDescription键及相应描述以访问相册:

ios,二维码,AVFoundation

然后在ViewController.m文件中添加UIImagePickerControllerDelegate和UINavigationControllerDelegate协议:

 

复制代码
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

 

在实现部分找到readingFromAlbum:方法,添加下面代码以访问相册中的图片:


- (IBAction)readingFromAlbum:(id)sender
{
 UIImagePickerController *picker = [[UIImagePickerController alloc] init];
 picker.delegate = self;
 picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
 picker.allowsEditing = YES;
 
 [self presentViewController:picker animated:YES completion:nil];
}

然后实现UIImagePickerControllerDelegate的imagePickerController:didFinishPickingMediaWithInfo:方法以解析选取的二维码图片:


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
 [picker dismissViewControllerAnimated:YES completion:nil];
 
 UIImage *selectedImage = [info objectForKey:UIImagePickerControllerEditedImage];
 CIImage *ciImage = [[CIImage alloc] initWithImage:selectedImage];
 
 CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyLow}];
 NSArray *features = [detector featuresInImage:ciImage];
 
 if (features.count > 0) {
  CIQRCodeFeature *feature = features.firstObject;
  NSString *message = feature.messageString;
  
  // display message
  [self displayMessage:message];
  
  // play sound
  if (self.audioPlayer) {
   [self.audioPlayer play];
  }
 }
}