<strong>首先要想实现二维码的调试必须要真机才可以</strong>
<strong>
</strong>
<strong>1.首先要倒入AVFoundation这个框架.</strong>
<pre name="code" class="objc">/** Label用于显示获取到的二维码的信息的连线 */
@property (weak, nonatomic) IBOutlet UILabel *label;
/** 二维码生成的绘画 */
@property (nonatomic, strong) AVCaptureSession *session;
/** 二维码生成的图层 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
2.在touchBegan方法中实现二维码的扫描.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self readQRcode];
}
<strong>3.具体方法实现.</strong><pre name="code" class="objc">- (void)readQRcode
{
// 1. 摄像头设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 2. 设置输入
// 因为模拟器是没有摄像头的,因此在此最好做一个判断
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (error) {
NSLog(@"没有摄像头-%@", error.localizedDescription);
return;
}
// 3. 设置输出(Metadata元数据)
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 3.1 设置输出的代理
//ps:使用住队列效果更好
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// [output setMetadataObjectsDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
// 4. 拍摄会话
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// 添加session的输入和输出
[session addInput:input];
[session addOutput:output];
// 4.1 设置输出的格式
// 提示:一定要先设置会话的输出为output之后,再指定输出的元数据类型!
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 5. 设置预览图层(用来让用户能够看到扫描情况)
AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
// 5.1 设置preview图层的属性
[preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
// 5.2 设置preview图层的大小
[preview setFrame:self.view.bounds];
// 5.3 将图层添加到视图的图层
[self.view.layer insertSublayer:preview atIndex:0];
self.previewLayer = preview;
// 6. 启动会话
[session startRunning];
}
<strong>4.实现代理方法.</strong>
<pre name="code" class="objc">#pragma mark -代理方法.
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
NSLog(@"%@",metadataObjects);
}