從iOS7開始集成了二維碼的生成和讀取功能,在此前被廣泛使用的zbarsdk目前不支持64位處理器
掃描二維碼的步驟:
導(dǎo)入AVFoundation框架
-
利用攝像頭識別二維碼中的內(nèi)容
- 輸入(攝像頭)
- 由會話將攝像頭采集到的二維碼圖像轉(zhuǎn)換成字符串?dāng)?shù)據(jù)
- 輸出(數(shù)據(jù))
- 由預(yù)覽圖層顯示掃描場景
代碼如下:
//
// ScanQRCodeViewController.m
// 02-掃描二維碼
//
// Created by 龐小江 on 2016/11/2.
// Copyright ? 2016年 Paul. All rights reserved.
//
#import "ScanQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ScanQRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, weak) AVCaptureSession *session;
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
@end
@implementation ScanQRCodeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createScanQRCode];
}
- (void)createScanQRCode {
// 1.創(chuàng)建捕捉回話
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 2.添加輸入設(shè)備(數(shù)據(jù)從攝像頭輸入)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 3.添加輸出數(shù)據(jù)
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 設(shè)置代理
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:output];
// 3.1設(shè)置輸入元數(shù)據(jù)的類型
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 4.添加掃描圖層
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];
self.layer = layer;
// 5.開始掃描
[session startRunning];
}
#pragma mark - 實現(xiàn)output的回調(diào)方法
// 當(dāng)掃描到數(shù)據(jù)時就會執(zhí)行該方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
// 停止掃描
[self.session stopRunning];
// 將預(yù)覽圖層移除
[self.layer removeFromSuperlayer];
} else {
NSLog(@"沒有掃描到數(shù)據(jù)");
}
}
效果圖如下:

D1E759A8849916383D9B51D38C8E06FD.jpg