在 iOS 上做二維碼掃描,早期常見的第三方庫有 ZBar 與 ZXing。本文要介紹的是 iOS 7.0 之後,AVFoundation 框架原生的二維碼掃描能力,無需引入任何第三方依賴。
第一步,將 AVFoundation.framework 加入工程的 Build Phase 中「Link Binary With Libraries」清單,即可開始。
一、搭建 UI
先在介面 Builder 中布置好預覽容器、狀態標籤與開始/停止按鈕,並建立對應的 IBOutlet 與 IBAction:
@property (weak, nonatomic) IBOutlet UIView *viewPreview; @property (weak, nonatomic) IBOutlet UILabel *lblStatus; @property (weak, nonatomic) IBOutlet UIButton *startBtn; - (IBAction)startStopReading:(id)sender;
二、控制器設定
導入 AVFoundation 框架,並讓控制器實作 AVCaptureMetadataOutputObjectsDelegate 協議:
#import <AVFoundation/AVFoundation.h> @interface ViewController () <AVCaptureMetadataOutputObjectsDelegate> @property (strong, nonatomic) UIView *boxView; @property (nonatomic) BOOL isReading; @property (strong, nonatomic) CALayer *scanLayer; @property (nonatomic, strong) AVCaptureSession *captureSession; // 捕捉會話 @property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer; // 預覽圖層 @end
在 viewDidLoad 中初始化,並在 startReading 方法中完成掃描的所有配置——這是整段功能的重點:
- (void)viewDidLoad {
[super viewDidLoad];
_captureSession = nil;
_isReading = NO;
}
- (BOOL)startReading {
NSError *error;
// 1. 初始化捕捉設備(相機)
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 2. 以設備建立輸入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (!input) {
NSLog(@"%@", [error localizedDescription]);
return NO;
}
// 3. 建立元數據輸出流
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
// 4. 建立捕捉會話並加入輸入、輸出
_captureSession = [[AVCaptureSession alloc] init];
[_captureSession addInput:input];
[_captureSession addOutput:captureMetadataOutput];
// 5. 建立佇列並設定代理與輸出類型
dispatch_queue_t dispatchQueue = dispatch_queue_create("myQueue", NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
[captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 6. 建立預覽圖層
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];
// 7. 設定掃描範圍
captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
// 掃描框
_boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height * 0.2f, _viewPreview.bounds.size.width * 0.6f, _viewPreview.bounds.size.height * 0.6f)];
_boxView.layer.borderColor = [UIColor greenColor].CGColor;
_boxView.layer.borderWidth = 1.0f;
[_viewPreview addSubview:_boxView];
// 掃描線
_scanLayer = [[CALayer alloc] init];
_scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
_scanLayer.backgroundColor = [UIColor brownColor].CGColor;
[_boxView.layer addSublayer:_scanLayer];
[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
// 8. 開始掃描
[_captureSession startRunning];
return YES;
}
實作代理方法以取得掃描結果,並讓掃描線上下移動營造動效:
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
[_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
_isReading = NO;
}
}
}
- (void)moveScanLayer:(NSTimer *)timer {
CGRect frame = _scanLayer.frame;
if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
frame.origin.y = 0;
_scanLayer.frame = frame;
} else {
frame.origin.y += 5;
[UIView animateWithDuration:0.1 animations:^{ _scanLayer.frame = frame; }];
}
}
- (IBAction)startStopReading:(id)sender {
if (!_isReading) {
if ([self startReading]) {
[_startBtn setTitle:@"Stop" forState:UIControlStateNormal];
[_lblStatus setText:@"Scanning for QR Code"];
}
} else {
[self stopReading];
[_startBtn setTitle:@"Start!" forState:UIControlStateNormal];
}
_isReading = !_isReading;
}
- (void)stopReading {
[_captureSession stopRunning];
_captureSession = nil;
[_scanLayer removeFromSuperlayer];
[_videoPreviewLayer removeFromSuperlayer];
}
透過上述流程,即可在 iOS 原生環境下完成一個具備掃描框與掃描線動效的二維碼掃描器,完全不必依賴第三方庫。