112 系統自帶二維碼掃描

1.生成二維碼:

- (void)getImage{
    // 1.實例化二維碼濾鏡
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

    // 2.恢復濾鏡的默認屬性 (因爲濾鏡有可能保存上一次的屬性)
    [filter setDefaults];

    // 3.將字符串轉換成NSdata
    NSData *data  = [@"http://www.itheima.com" dataUsingEncoding:NSUTF8StringEncoding];

    // 4.通過KVO設置濾鏡, 傳入data, 將來濾鏡就知道要通過傳入的數據生成二維碼
    [filter setValue:data forKey:@"inputMessage"];

    // 5.生成二維碼
     CIImage *outputImage = [filter outputImage];

    UIImage *image = [UIImage  imageWithCIImage:outputImage];
}

2.掃描二維碼:
1>需要的屬性和頭文件:

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@end

2>實例化對象:

- (void)saomiao {
    // 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];
}

3>掃描後的代理方法:

- (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或者名片等信息進行掃描,可以在此進行擴展!
        NSLog(@"%@", obj.stringValue);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章