近幾年二維碼幾乎無所不在,從付款、加好友到網頁登入,掃描 QR Code 已經成為 App 必備的基础功能。在 iOS 上,只要善用 AVFoundation 框架,就能以很少的程式碼完成相機取景與二維碼辨識。本文記錄了完整的實作步驟與範例。
整體流程可以拆成幾個環節:
-- 導入 AVFoundation 框架:#import <AVFoundation/AVFoundation.h>
1. 利用攝影機辨識二維碼中的內容(注意:模擬器無法使用相機)。
2. 輸入來源為攝影機。
3. 由「拍攝工作階段(AVCaptureSession)」把相機擷取到的影像轉換為字串資料。
4. 輸出即為解析後的資料。
5. 由「預覽圖層」負責顯示掃描畫面。
#import ViewController.h #import @interface ViewController ()vcapturemetadataoutputobjectsdelegate> @property (nonatomic, strong) AVCaptureSession *session; @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 1. 實例化拍攝設備 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; // 2. 設置輸入設備 AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; // 3. 設置元數據輸出 // 3.1 實例化拍攝元數據輸出 AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init]; // 3.3 設置輸出數據代理 [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; // 4. 添加拍攝會話 // 4.1 實例化拍攝會話 AVCaptureSession *session = [[AVCaptureSession alloc] init]; // 4.2 添加會話輸入 [session addInput:input]; // 4.3 添加會話輸出 [session addOutput:output]; // 4.3 設置輸出數據類型,需要將元數據輸出添加到會話後,才能指定元數據類型,否則會報錯 [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; self.session = session; // 5. 視頻預覽圖層 // 5.1 實例化預覽圖層, 傳遞_session是為了告訴圖層將來顯示什麼內容 AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_session]; preview.videoGravity = AVLayerVideoGravityResizeAspectFill; preview.frame = self.view.bounds; // 5.2 將圖層插入當前視圖 [self.view.layer insertSublayer:preview atIndex:100]; self.previewLayer = preview; // 6. 啟動會話 [_session startRunning]; } #pragma mark - AVCaptureMetadataOutputObjectsDelegate 代理方法 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { // 會頻繁的掃描,調用代理方法 // 1. 如果掃描完成,停止會話 [self.session stopRunning]; // 2. 刪除預覽圖層 [self.previewLayer removeFromSuperlayer]; NSLog(@%@, metadataObjects); // 3. 設置界面顯示掃描結果 if (metadataObjects.count > 0) { AVMetadataMachineReadableCodeObject *obj = metadataObjects[0]; // 提示:如果需要對url或者名片等信息進行掃描,可以在此進行擴展! // _label.text = obj.stringValue; NSLog(@%@, obj.stringValue); } }
整個掃描機制的核心是 AVCaptureSession:它把「輸入(相機)」與「輸出(元資料)」串接起來,並透過代理方法即時回傳辨識結果。由於掃描過程會頻繁觸發代理,因此一旦成功取得結果,就應該立即停止工作階段並移除預覽圖層,避免資源浪費。
此外,設定輸出資料型別(setMetadataObjectTypes:)必須在把 metadataOutput 加入 session 之後進行,否則會引發錯誤。若要擴充支援條碼、名片等其他格式,只需調整 metadataObjectTypes 陣列即可。