iOS自带的条码扫描比第三方库要快一些
首先要导入#import
//二维码生成的会话
@property (nonatomic, strong) AVCaptureSession *mySession;
//二维码生成的图层
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *myPreviewLayer;
@end
@implementation ScanningViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"扫描";
//扫描二维码
[self readQRcode];
}
-(void)viewDidAppear:(BOOL)animated{
[self.mySession startRunning];
}
#pragma mark - 扫描条码
-(void)readQRcode
{
//1、获取摄像头设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//2、设置输入
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (error) {
NSLog(@"没有摄像头:%@", error.localizedDescription);
return;
}
//3、设置输出(metadata 元数据)
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//4、创建拍摄会话
AVCaptureSession *session = [[AVCaptureSession alloc] init];
//添加session的输入和输出
[session addInput:input];
[session addOutput:output];
// 4.1 设置输出的格式
// 提示:一定要先设置会话的输出为output之后,再指定输出的元数据类型!
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code]];
// 5. 设置预览图层(用来让用户能够看到扫描情况)
AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
// 5.1 设置preview图层的属性
[preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
// 5.2 设置preview图层的大小
[preview setFrame:self.view.bounds];
// 5.3 将图层添加到视图的图层
[self.view.layer insertSublayer:preview atIndex:0];
// 6. 启动会话
[session startRunning];
self.myPreviewLayer = preview;
self.mySession = session;
}
#pragma mark - 输出代理方法
// 此方法是在识别到QRCode,并且完成转换
// QRCode的内容越大,转换需要的时间就越长
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
// 会频繁的扫描,调用代理方法
// 1. 如果扫描完成,停止会话
[self.mySession stopRunning];
// 2. 删除预览图层
// [self.myPreviewLayer removeFromSuperlayer];
NSLog(@"%@", metadataObjects);
// 3. 设置界面显示扫描结果
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
ScanResultViewController *scanResultVC = [[ScanResultViewController alloc]init];
//将扫描到的文字显示
scanResultVC.textStr = obj.stringValue;
//跳转页面
[self.navigationController pushViewController:scanResultVC animated:YES];
}
}
604

被折叠的 条评论
为什么被折叠?



