您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 7 起內建的條碼掃描 API 實作教學

編輯:iOS 開發綜合

原本專案用的是 ZBar 這套開源庫來做條碼掃描,但它已經不再支援 arm64 架構,也遲遲沒有更新,只好改用 iOS 7 之後 Apple 內建的 AVFoundation 掃描 API。

介面準備

先在 xib 上擺一個 viewPreview,用來承載相機預覽畫面:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface QRCodeReadController : BaseViewController <AVCaptureMetadataOutputObjectsDelegate>

@property (weak, nonatomic) IBOutlet UIView *viewPreview;

@end

實作細節

@interface QRCodeReadController () {
    NSInteger maxY;
    NSInteger minY;
    NSTimer *timer;
    UIImageView *line;
}

@property (nonatomic) BOOL isReading;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

- (BOOL)startReading;
- (void)stopReading;

@end

@implementation QRCodeReadController

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

    if ([self startReading]) {
        maxY = 280;
        minY = 2;

        // 掃描線動畫
        line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 280, 10)];
        [line setImage:[UIImage imageNamed:@"e0"]];
        [_viewPreview addSubview:line];

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 40
                                                target:self
                                              selector:@selector(move)
                                              userInfo:nil
                                               repeats:YES];
    }
}

AVCaptureMetadataOutput 這個類別,搭配 AVCaptureMetadataOutputObjectsDelegate 協定,負責攔截輸入裝置取得的後設資料(也就是相機拍到的條碼內容),並轉譯成人類可讀的字串格式。

- (BOOL)startReading {
    NSError *error;

    AVCaptureDevice *captureDevice =
        [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input =
        [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }

    _captureSession = [[AVCaptureSession alloc] init];
    [_captureSession addInput:input];

    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_captureSession addOutput:captureMetadataOutput];

    dispatch_queue_t dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];

    // 用 AVCaptureVideoPreviewLayer 把相機畫面呈現給使用者
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    [_viewPreview.layer addSublayer:_videoPreviewLayer];

    [_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]) {
            [self performSelectorOnMainThread:@selector(stopReading)
                                  withObject:nil
                               waitUntilDone:NO];
            NSLog(@"掃描結果 = %@", [metadataObj stringValue]);
            _isReading = NO;
        }
    }
}

- (void)stopReading {
    [_captureSession stopRunning];
    _captureSession = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}

// 掃描線上下往返移動
- (void)move {
    static BOOL flag = YES;   // YES 向下,NO 向上

    if (flag) {
        if (line.frame.origin.y < maxY) {
            line.frame = CGRectMake(line.frame.origin.x,
                                    line.frame.origin.y + 5,
                                    line.frame.size.width,
                                    line.frame.size.height);
        } else {
            flag = !flag;
        }
    } else {
        if (line.frame.origin.y > minY) {
            line.frame = CGRectMake(line.frame.origin.x,
                                    line.frame.origin.y - 5,
                                    line.frame.size.width,
                                    line.frame.size.height);
        } else {
            flag = !flag;
        }
    }
}

@end

幾個實作上容易出錯的地方:dispatch_queue_create 的字串參數必須是 C 字串常量而非 NSString;setMetadataObjectTypes: 要設定成想支援的類型(QRCode、EAN13、PDF417 等),設定不當會拋出例外;由於回呼是在背景佇列觸發,任何 UI 操作都必須切回主線程。另外別忘了在 viewWillDisappear 中移除 timer,否則畫面離開後計時器仍在跑。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved