扫一扫功能(二维码、条形码)

实现这样一个效果效果

UIbuttonClick_2.gif

先引入这个框架

 #import 

然后只需要设置以下内容就可扫描到了

- (void)setupScaner {
    //初始化捕捉对象
    _captureSession = [[AVCaptureSession alloc]init];
    //初始化输入对象
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    [_captureSession addInput:input];
    //初始化输出对象
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];
    //设置扫描的内容(这设置就只扫条形码),ps:通常放在主线程,如果在子线程回调会很慢
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, nil]];
    //初始化显示层(将相机capture到的内容展示到layer层上)
    AVCaptureVideoPreviewLayer *videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [videoPreviewLayer setFrame:self.view.layer.bounds];
    [self.view.layer addSublayer:videoPreviewLayer];
    //开始
    [_captureSession startRunning];
}

最后只需在AVCaptureMetadataOutputObjectsDelegate中使用这个代理方法即可在获取到扫描内容后自定义操作

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj =[metadataObjects objectAtIndex:0];
        //metadataObj.stringValue就是扫描获得的文字,对他进行操作即可 
        //将获取到的nesting回传并popViewController就能实现gif的效果
    }
}

置于相框,还有别的有会移动线、是通过增加一些UIView、以及使用NSTimer来实现了。

你可能感兴趣的:(扫一扫功能(二维码、条形码))