從iOS7開始集成了二維碼的生成和讀取功能,在此前被廣泛使用的zbarsdk目前不支持64位處理器
掃描二維碼的步驟:
導入AVFoundation框架
-
利用攝像頭識別二維碼中的內容
- 輸入(攝像頭)
- 由會話將攝像頭采集到的二維碼圖像轉換成字符串數據
- 輸出(數據)
- 由預覽圖層顯示掃描場景
代碼如下:
//
// 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.創建捕捉回話
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 2.添加輸入設備(數據從攝像頭輸入)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 3.添加輸出數據
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 設置代理
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:output];
// 3.1設置輸入元數據的類型
[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 - 實現output的回調方法
// 當掃描到數據時就會執行該方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
// 停止掃描
[self.session stopRunning];
// 將預覽圖層移除
[self.layer removeFromSuperlayer];
} else {
NSLog(@"沒有掃描到數據");
}
}
效果圖如下:
D1E759A8849916383D9B51D38C8E06FD.jpg