1.核心代码
启动摄像头
- (void)setupCamera
{
// Device
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
// Output
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
session = [[AVCaptureSession alloc]init];
[session setSessionPreset:AVCaptureSessionPresetHigh];
if ([session canAddInput:input])
{
[session addInput:input];
}
if ([session canAddOutput:output])
{
[session addOutput:output];
}
// 条码类型 AVMetadataObjectTypeQRCode
if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];//[NSArray arrayWithObject:AVMetadataObjectTypeQRCode];
}
// Preview
AVCaptureVideoPreviewLayer *preview =[AVCaptureVideoPreviewLayer layerWithSession:session];
preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
CGRect imageViewFrame = imageView.frame;
preview.frame = CGRectMake(imageViewFrame.origin.x + 10, imageViewFrame.origin.y + 10, imageViewW - 20, imageViewW - 20);
[self.view.layer insertSublayer:preview atIndex:0];
// Start
[session startRunning];
}
扫描完成后的回调处理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (scanIsOK) return;
scanIsOK = YES;
NSString *stringValue;
if ([metadataObjects count] > 0)
{
AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
}
[session stopRunning];
[timer invalidate];
timer = nil;
if ([UIUtils checkURL:stringValue]) {
}else{
}
}
demo下载地址
ios7自带的二维码扫描