1.代碼如下:
#import "ViewController.h"
#import
@interface ViewController ()
@property (nonatomic, weak) AVCaptureSession *session;
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 1.創(chuàng)建捕捉會話
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 2.添加輸入設備(數(shù)據(jù)從攝像頭輸入)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 3.添加輸出數(shù)據(jù)(示例對象-->類對象-->元類對象-->根元類對象)
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:output];
// 3.1.設置輸入元數(shù)據(jù)的類型(類型是二維碼數(shù)據(jù))
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 4.添加掃描圖層
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];
self.layer = layer;
// 5.開始掃描
[session startRunning];
}
#pragma mark - 實現(xiàn)output的回調方法
// 當掃描到數(shù)據(jù)時就會執(zhí)行該方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
// 停止掃描
[self.session stopRunning];
// 將預覽圖層移除
[self.layer removeFromSuperlayer];
} else {
NSLog(@"沒有掃描到數(shù)據(jù)");
}
}
@end