AJ學IOS 之二維碼學習,快速打開相機讀取二維碼

AJ分享,必須精品markdown

 

上一篇文章寫了怎麼生成二維碼,這兒就說說怎麼讀取吧,反正也很簡單,iOS封裝的太強大了session

步驟呢就是這樣:
讀取二維碼須要導入AVFoundation框架#import <AVFoundation/AVFoundation.h>
1:利用攝像頭識別二維碼中的內容(模擬器不行)。
2:輸入(攝像頭)。
3:由會話將攝像頭採集到的二維碼圖像轉換成字符串數據。
4:輸出(數據)。
5:由預覽圖層顯示掃描場景。框架

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@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);
    }
}
相關文章
相關標籤/搜索