- 輸入設(shè)備
- 輸出設(shè)備
- 會話
- 預(yù)覽圖層
- 開啟會話
導(dǎo)入框架 權(quán)限
#import <AVFoundation/AVFoundation.h>
<key>NSCameraUsageDescription</key>
<string></string>
輸入設(shè)備
//輸出設(shè)備
@property(strong,nonatomic)AVCaptureDeviceInput *deviceInput;
//----------------------------------------------------------------
//1.1攝像頭的設(shè)備 默認(rèn)后置攝像頭
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//1.2創(chuàng)建攝像頭的輸入設(shè)備
self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
輸出設(shè)備
//輸出設(shè)備 Metadata元數(shù)據(jù)
@property(strong,nonatomic)AVCaptureMetadataOutput *output;
//----------------------------------------------------------------
//2.輸出設(shè)備 ->解析數(shù)據(jù)
self.output = [[AVCaptureMetadataOutput alloc] init];
//設(shè)置代理 用來獲取數(shù)據(jù)
[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
//掃描到二維碼數(shù)據(jù)時調(diào)用
//metadataObjects:掃描到的數(shù)據(jù)
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
//掃描到數(shù)據(jù)之后 移除圖層
[self.previewLayer removeFromSuperlayer];
//停止會話
[self.session stopRunning];
for (AVMetadataMachineReadableCodeObject *objc in metadataObjects) {
//二維碼掃描出來的結(jié)果是字符串
NSLog(@"%@",objc.stringValue);
//創(chuàng)建safari控制器#import <SafariServices/SafariServices.h>
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:objc.stringValue]];
[self presentViewController:safariVC animated:YES completion:nil];
}
}
會話
//會話
@property(nonatomic,strong)AVCaptureSession *session;
//----------------------------------------------------------------
//3.會話 ->連接輸入和輸出設(shè)備
self.session = [[AVCaptureSession alloc] init];
//連接設(shè)備
if([self.session canAddInput:self.deviceInput]){
[self.session addInput:self.deviceInput];
}
if([self.session canAddOutput:self.output]){
[self.session addOutput:self.output];
}
//設(shè)置輸出設(shè)備的解析數(shù)據(jù)的類型
//AVMetadataObjectTypeQRCode 二維碼
self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
預(yù)覽圖層
//圖層
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;
//-------------------------------------------------------------------------
//4.預(yù)覽的圖層
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//添加圖層
[self.view.layer addSublayer:self.previewLayer];
//設(shè)置圖層的大小
self.previewLayer.frame = self.view.bounds;
開啟會話
//5.開啟會話
[self.session startRunning];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者