[关闭]
@chenbinghua 2015-09-12T10:36:31.000000Z 字数 1700 阅读 1523

iOS开发之扫描二维码

iOS笔记


读取二维码需要导入AVFoundation框架
利用摄像头识别二维码中的内容(模拟器不行)

  1. #import "ViewController.h"
  2. #import <AVFoundation/AVFoundation.h>
  3. @interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>
  4. @property (nonatomic, weak) AVCaptureSession *session;
  5. @property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
  6. @end
  7. @implementation ViewController
  8. - (void)viewDidLoad {
  9. [super viewDidLoad];
  10. }
  11. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  12. {
  13. // 1.创建捕捉会话
  14. AVCaptureSession *session = [[AVCaptureSession alloc] init];
  15. self.session = session;
  16. // 2.添加输入设备(数据从摄像头输入)
  17. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  18. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
  19. [session addInput:input];
  20. // 3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
  21. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  22. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  23. [session addOutput:output];
  24. // 3.1.设置输入元数据的类型(类型是二维码数据)
  25. [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
  26. // 4.添加扫描图层
  27. AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
  28. layer.frame = self.view.bounds;
  29. [self.view.layer addSublayer:layer];
  30. self.layer = layer;
  31. // 5.开始扫描
  32. [session startRunning];
  33. }
  34. #pragma mark - 实现output的回调方法
  35. // 当扫描到数据时就会执行该方法
  36. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  37. {
  38. if (metadataObjects.count > 0) {
  39. AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
  40. NSLog(@"%@", object.stringValue);
  41. // 停止扫描
  42. [self.session stopRunning];
  43. // 将预览图层移除
  44. [self.layer removeFromSuperlayer];
  45. } else {
  46. NSLog(@"没有扫描到数据");
  47. }
  48. }
  49. @end
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注