iOS 二维码扫描相关功能实现

2020-01-21 07:13:15丽君

block:


typedef void(^GetBrightnessBlock)(CGFloat brightness);//用来向外部传递捕获到的亮度值以便于识别何时开启闪光灯,
typedef void(^ScanBlock)(NSArray *metadataObjects);//捕获到的结果集合
//亮度回调
- (void)brightnessChange:(GetBrightnessBlock)getBrightnessBlock;
//扫描结果
- (void)scanResult:(ScanBlock)scanBlock;

- (void)startRunning {
 [_session startRunning];
}
- (void)stopRunning {
 [_session stopRunning];
}

需要遵循:/**
 重置根据光线强弱值打开手电筒 delegate方法
 */
- (void)resetSampleBufferDelegate;
/**
 取消根据光线强弱值打开手电筒的delegate方法
 */
- (void)cancelSampleBufferDelegate;
- (void)resetSampleBufferDelegate {
 [_videoDataOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
}
- (void)cancelSampleBufferDelegate {
 [_videoDataOutput setSampleBufferDelegate:nil queue:dispatch_get_main_queue()];
}

#pragma mark 播放扫描提示音
- (void)playSoundName:(NSString *)name {
 NSString *audioFile = [[NSBundle mainBundle] pathForResource:name ofType:nil];
 NSURL *fileUrl = [NSURL fileURLWithPath:audioFile];
 SystemSoundID soundID = 0;
 AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
 AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
 AudioServicesPlaySystemSound(soundID); // 播放音效
}
void soundCompleteCallback(SystemSoundID soundID, void *clientData){
  
}

注:这里只是截取部分重要代码,具体功能我会将代码放到GitHub上,代码里注释也写的很明白

使用功能

开启、结束定时器

开启、关闭session会话

启用、移除sampleBuffer代理


- (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 [self.scanView addTimer];
 [_scanManager startRunning];
 [_scanManager resetSampleBufferDelegate];
}
- (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 [self.scanView removeTimer];
 [_scanManager stopRunning];
 [_scanManager cancelSampleBufferDelegate];
}