導入框架 權限
#import <AVFoundation/AVFoundation.h>
<key>NSCameraUsageDescription</key>
<string></string>
輸入設備
//輸出設備
@property(strong,nonatomic)AVCaptureDeviceInput *deviceInput;
//----------------------------------------------------------------
//1.1攝像頭的設備 默認后置攝像頭
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//1.2創(chuàng)建攝像頭的輸入設備
self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
輸出設備
//輸出設備 Metadata元數(shù)據(jù)
@property(strong,nonatomic)AVCaptureMetadataOutput *output;
//----------------------------------------------------------------
//2.輸出設備 ->解析數(shù)據(jù)
self.output = [[AVCaptureMetadataOutput alloc] init];
//設置代理 用來獲取數(shù)據(jù)
[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
//掃描到二維碼數(shù)據(jù)時調用
//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) {
//二維碼掃描出來的結果是字符串
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.會話 ->連接輸入和輸出設備
self.session = [[AVCaptureSession alloc] init];
//連接設備
if([self.session canAddInput:self.deviceInput]){
[self.session addInput:self.deviceInput];
}
if([self.session canAddOutput:self.output]){
[self.session addOutput:self.output];
}
//設置輸出設備的解析數(shù)據(jù)的類型
//AVMetadataObjectTypeQRCode 二維碼
self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
預覽圖層
//圖層
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;
//-------------------------------------------------------------------------
//4.預覽的圖層
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//添加圖層
[self.view.layer addSublayer:self.previewLayer];
//設置圖層的大小
self.previewLayer.frame = self.view.bounds;
開啟會話
//5.開啟會話
[self.session startRunning];
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。