2.iOS7上扫一次码,会触发无数次delegate方法.只能做判断.
下面是相关代码:
- (id)initWithView:(UIView *)_viewLayer finishBlock:(void(^)(NSArray *metadataObjects,BOOL success))block {
if (self = [super init]) {
self.superView = _viewLayer;
self.finishBlock = block;
// [self setupCamera];
}
return self;
}
- (void)dealloc {
[_session stopRunning];
}
- (void)setupCamera
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
isReading = YES;
// 耗时的操作
// Device
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
// 条码类型 AVMetadataObjectTypeQRCode
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
dispatch_async(dispatch_get_main_queue(), ^{
// 更新界面
// Preview
_preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame = self.superView.bounds;
[self.superView.layer insertSublayer:self.preview atIndex:0];
// Start
[_session startRunning];
});
});
}
- (void)startScaning {
if (!_session) {//坑爹的iOS7startRunning只能有效一次
[self setupCamera];
}
}
- (void)stopScaning {//坑爹的iOS7startRunning只能有效一次,只能全部重置为nil在重新生成
[self.session stopRunning];
[self.preview removeFromSuperlayer];
self.session = nil;
self.preview = nil;
self.device = nil;
self.input = nil;
self.output = nil;
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (!isReading) {//坑爹的iOS7扫一次二维码会不停的触发代理方法
return;
}
if ([metadataObjects count] >0)
{
if (self.finishBlock) {
self.finishBlock(metadataObjects,YES);
}
isReading = NO;
}
}