iOS开发扫描二维码

首先要引入AVFoundation框架并遵守AVCaptureMetadataOutputObjectsDelegate协议, 通过代理方法获取扫描结果

#import 
@interface ViewController ()

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self action];
}


- (void)action {
    // 1
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 2
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    // 3
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 4
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    output.rectOfInterest = CGRectMake(0.05, 0.2, 0.7, 0.6);
    // 5
    self.session = [[AVCaptureSession alloc] init];
    
    [_session addInput:input];
    
    [_session addOutput:output];
    
    // 6
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
    
    // 7
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.frame = self.view.layer.bounds;
    
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    
    [_session startRunning];
    
}
#pragma mark - capture delegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects && metadataObjects.count>0)
    {
        //stop the capture
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //do sth to handle the capture result
        [self performSelectorOnMainThread:@selector(handleResult:) withObject:metadataObject waitUntilDone:NO];
    }
}

- (void)handleResult:(AVMetadataMachineReadableCodeObject *)metadataObject
{
    
    NSLog(@"%@", metadataObject.type);
    if([metadataObject.type isEqualToString:AVMetadataObjectTypeQRCode])
        NSLog(@"QR code");
    else
        NSLog(@"other code");
    
    NSString *captureStr = metadataObject.stringValue;
    NSLog(@"%@",captureStr);
    self.textField.text = captureStr;
    [self.previewLayer removeFromSuperlayer];
}

你可能感兴趣的:(iOS开发扫描二维码)