您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 原生二維碼掃描實作

編輯:iOS 相關教學

做 iOS 的二維碼掃描,過去有 ZBar 和 ZXing 兩個第三方庫可選。本文要介紹的,是 iOS 7.0 之後 AVFoundation 框架提供的原生二維碼掃描。

首先,需要把 AVFoundation.framework 框架加到專案 Build Phases 的「Link Binary With Libraries」之下,然後就可以開始了。

一、搭建 UI

IBOutlet、IBAction 如下:

@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (weak, nonatomic) IBOutlet UILabel *lblStatus;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
- (IBAction)startStopReading:(id)sender;

二、控制器 ViewController

首先導入 AVFoundation 框架,並讓控制器實作 AVCaptureMetadataOutputObjectsDelegate 協議:

#import <AVFoundation/AVFoundation.h>

@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>

整體 property 如下:

@property (strong, nonatomic) UIView *boxView;
@property (nonatomic) BOOL isReading;
@property (strong, nonatomic) CALayer *scanLayer;
- (BOOL)startReading;
- (void)stopReading;

// 捕捉會話
@property (nonatomic, strong) AVCaptureSession *captureSession;
// 展示 layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

在 viewDidLoad 中初始化:

- (void)viewDidLoad {
    [super viewDidLoad];
    _captureSession = nil;
    _isReading = NO;
}

接著實作 startReading 方法(這是重點):

- (BOOL)startReading {
    NSError *error;
    // 1. 初始化捕捉設備,類型為 Video
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 2. 用 captureDevice 建立輸入流
    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];
    // 設定輸出媒體資料類型為 QRCode
    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    // 6. 實例化預覽圖層
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    // 7. 設定填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    // 8. 設定圖層 frame
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    // 9. 加到預覽 view 的圖層上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    // 10. 設定掃描範圍
    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 - _viewPreview.bounds.size.width * 0.4f,
        _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.4f)];
    _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 *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self
                                                    selector:@selector(moveScanLayer:)
                                                    userInfo:nil repeats:YES];
    [timer fire];
    // 開始掃描
    [_captureSession startRunning];
    return YES;
}

實作 AVCaptureMetadataOutputObjectsDelegate 協議方法:

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (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;
        }
    }
}

實作計時器方法 moveScanLayer::

- (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];
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved