iOS实现一个简单的扫码功能

Posted Neo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS实现一个简单的扫码功能相关的知识,希望对你有一定的参考价值。

用到的是AVFoundation

需要用到Capture,Input,Output,Session,previewLayer相关类

#import "ScanQRCodeController.h"
#import <AVFoundation/AVFoundation.h>
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ScanQRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic,strong)AVCaptureSession  *session;
@property (nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;
@end

@implementation ScanQRCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _session = [[AVCaptureSession alloc]init];
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:&error];
    if (error) {
        NSLog(@"初始化input失败,%@",error);
        return;
    }
    if ([_session canAddInput:input]) {
        [_session addInput:input];
        NSLog(@"添加input成功");
    }else{
        NSLog(@"添加input失败");
        return;
    }
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    if ([_session canAddOutput:output]) {
        [_session addOutput:output];
        NSLog(@"添加output成功");
    }else{
        NSLog(@"添加output失败");
        return;
    }
    
    [output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,nil]];
    
    dispatch_queue_t dispatchQueue = dispatch_queue_create("myQueue", NULL);
    
    [output setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:_session];
    [_previewLayer setFrame:self.view.layer.bounds];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    //10.设置扫描范围
//    output.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.6f, 0.6f);
    //10.开始扫描
    [_session startRunning];
    NSLog(@"开始扫描");
}


- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    NSLog(@"come:%@",metadataObjects);
}

@end

注意:

1.输出类型错误的话,没有输出

扫描条形码

    [output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,nil]];

扫描二维码

    [output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,nil]];

2.设置output的类型必须在执行addOutput方法之后,否则会崩溃

 

以上是关于iOS实现一个简单的扫码功能的主要内容,如果未能解决你的问题,请参考以下文章

基于 zbar 的,简单易用高性能的扫码器

扫码登录的简单实现

3D Touch的简单使用

JS实现App扫码网页端登录

真香!想不到吧?用Python写的扫码程序这么赞

uniapp App端小程序 连续扫码添加购物车功能