@import AVFoundation;
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
_output = [[AVCaptureMetadataOutput alloc] init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
_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];
}
if ( [_output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode] )
{
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
}
_preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame = self.view.bounds;
[self.view.layer insertSublayer:self.preview atIndex:0];
[_session startRunning];
{
UIImage* image = [UIImage imageNamed:@"pickbg"];
CGRect newframe = CGRectMake(0,
CGRectGetMinY(self.view.frame) + 20,
image.size.width,
image.size.height);
_logoImageView =[[UIImageView alloc] initWithFrame:newframe];
_logoImageView.center = CGPointMake(self.view.center.x, CGRectGetHeight(self.view.bounds) * 0.5 );
_logoImageView.image = image;
[self.view addSubview:_logoImageView];
self.linelayer = [[CALayer alloc]init];
self.linelayer.frame = CGRectMake((_logoImageView.frame.size.width-200)/2, 10, 200, 2);
self.linelayer.backgroundColor = [UIColor redColor].CGColor;
[_logoImageView.layer addSublayer:self.linelayer];
}
-(void)openAction
{
[_device lockForConfiguration:nil];
if (!_isLightOn)
{
[_device setTorchMode:AVCaptureTorchModeOn];
_isLightOn = YES;
}
else
{
[_device setTorchMode:AVCaptureTorchModeOff];
_isLightOn = NO;
}
[_device unlockForConfiguration];
}
#pragma mark -AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection
{
NSString *stringValue;
if ([metadataObjects count] >0)
{
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
}
[_session stopRunning];
if ( [self.delegate respondsToSelector:@selector(qrScanViewController:didFinishQRScanWithResult:)] )
{
[self.delegate qrScanViewController:self didFinishQRScanWithResult:stringValue];
}
}