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

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

然后在接口部分添加一个AVAudioPlayer对象的属性:


@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

在实现部分添加loadSound方法及代码,并在viewDidLoad中调用该方法:


- (void)loadSound
{
 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];
 NSURL *soundURL = [NSURL URLWithString:soundFilePath];
 NSError *error;
 
 self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
 
 if (error) {
  NSLog(@"Could not play sound file.");
  NSLog(@"%@", [error localizedDescription]);
 }
 else {
  [self.audioPlayer prepareToPlay];
 }
}

- (void)viewDidLoad
{
 ... 
 [self loadSound];
}

最后,在captureOutput:didOutputMetadataObjects:fromConnection:方法中添加下面的代码来播放声音:


- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
 if (metadataObjects != nil && metadataObjects.count > 0) {
  AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
  if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]) {
   ...
   self.isReading = NO;
   
   // play sound
   if (self.audioPlayer) {
    [self.audioPlayer play];
   }
  }
 }

2.3.3 设置扫描框

目前点击Start按钮,整个视图范围都可以扫描二维码。现在,我们需要设置一个扫描框,以限制只有扫描框区域内的二维码被读取。在这里,将扫描区域设置为storyboard中添加的视图,即scanView。

在实现部分找到startReading方法,添加下面的代码:


- (void)startScanning
{
 // configure previewLayer
 ...
 
 // set the scanning area
 [[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
  metadataOutput.rectOfInterest = [self.previewLayer metadataOutputRectOfInterestForRect:self.scanView.frame];
 }];
 
 // start scanning
 ...
}

需要注意的是,rectOfInterest属性不能在设置 metadataOutput 时直接设置,而需要在AVCaptureInputPortFormatDescriptionDidChangeNotification通知里设置,否则 metadataOutputRectOfInterestForRect:方法会返回 (0, 0, 0, 0)。

为了让扫描框更真实的显示,我们需要自定义ScanView,为其绘制边框、四角以及扫描线。

首先打开ScanView.m文件,在实现部分重写initWithCoder:方法,为scanView设置透明的背景颜色:


- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
 self = [super initWithCoder:aDecoder];
 
 if (self) {
  self.backgroundColor = [UIColor clearColor];
 }
 
 return self;
}