iOS二维码扫描

引用头文件:

#import 

遵守协议


定义成员变量

@property (nonatomic) AVCaptureSession *captureSession;
@property (nonatomic) AVCaptureVideoPreviewLayer *videoPreviewLayer;

主要代码

//用于扫描二维码的view
UIView *qrView = [[UIView alloc] init];
qrView.frame = CGRectMake(kScreenWidth / 2 - 130, 120, 260, 400);
qrView.backgroundColor = [UIColor redColor];
[self.view addSubview:qrView];


// 获取 AVCaptureDevice 实例
NSError * error;
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 初始化输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (!input) {
    NSLog(@"%@", [error localizedDescription]);
    return ;
}
// 创建会话
_captureSession = [[AVCaptureSession alloc] init];
// 添加输入流
[_captureSession addInput:input];
// 初始化输出流
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
// 添加输出流
[_captureSession addOutput:captureMetadataOutput];

// 创建dispatch queue.
dispatch_queue_t dispatchQueue;
static const char *QRCodeQueueName = "QRCodeQueue";
dispatchQueue = dispatch_queue_create(QRCodeQueueName, NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
// 设置元数据类型 AVMetadataObjectTypeQRCode
[captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];

// 创建输出对象
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:qrView.layer.bounds];
[qrView.layer addSublayer:_videoPreviewLayer];
// 开始会话
[_captureSession startRunning];

扫描结果回调

#pragma AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
      fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result;
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            result = metadataObj.stringValue;
            NSLog(@"二维码扫描结果是:%@",result);
        } else {
            NSLog(@"不是二维码");
        }
        
    }
}

记得最后销毁控制器的时候停止会话

- (void)dealloc
{
    // 停止会话
    [_captureSession stopRunning];
    _captureSession = nil;
}

如有错误请大家指出(╯‵□′)╯︵┻━┻

你可能感兴趣的:(iOS二维码扫描)