iOS中掃描二維碼的實現

從iOS7開始集成了二維碼的生成和讀取功能,在此前被廣泛使用的zbarsdk目前不支持64位處理器

掃描二維碼的步驟:
  • 導入AVFoundation框架

  • 利用攝像頭識別二維碼中的內容

    1. 輸入(攝像頭)
    2. 由會話將攝像頭采集到的二維碼圖像轉換成字符串數據
    3. 輸出(數據)
    4. 由預覽圖層顯示掃描場景
代碼如下:
//
//  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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容