iOS掃描二維碼(支持iOS7以后的版本)

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.創建捕捉會話

AVCaptureSession *session = [[AVCaptureSession alloc] init];

self.session = session;

// 2.添加輸入設備(數據從攝像頭輸入)

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

[session addInput:input];

// 3.添加輸出數據(示例對象-->類對象-->元類對象-->根元類對象)

AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];

[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

[session addOutput:output];

// 3.1.設置輸入元數據的類型(類型是二維碼數據)

[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 - 實現output的回調方法

// 當掃描到數據時就會執行該方法

- (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(@"沒有掃描到數據");

}

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容