1. 程式人生 > >iOS 掃描二維碼

iOS 掃描二維碼

_device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

_input = [AVCaptureDeviceInputdeviceInputWithDevice:self.deviceerror:nil];

_output = [[AVCaptureMetadataOutputalloc] init];

    [_outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];

_session = [[AVCaptureSessionalloc

]init];

    [_sessionsetSessionPreset:AVCaptureSessionPresetHigh];

if ([_sessioncanAddInput:self.input])

    {

        [_session addInput:self.input];

    }

if ([_sessioncanAddOutput:self.output])

    {

        [_session addOutput:self.output];

    }

if ( [_output.availableMetadataObjectTypescontainsObject

:AVMetadataObjectTypeQRCode] )

    {

_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

    }

_preview = [AVCaptureVideoPreviewLayerlayerWithSession:self.session];

_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;

_preview.frame = self.view.bounds;

    [self.view.layerinsertSublayer:

self.previewatIndex:0];

    [_sessionstartRunning];

{

        UIImage* image = [UIImage imageNamed:@"pickbg"];

        CGRect newframe = CGRectMake(0,

                                     CGRectGetMinY(self.view.frame) + 20,

                                     image.size.width,

                                     image.size.height);

        _logoImageView =[[UIImageView alloc] initWithFrame:newframe];

        _logoImageView.center = CGPointMake(self.view.center.x, CGRectGetHeight(self.view.bounds) * 0.5 );

        _logoImageView.image = image;

        [self.view addSubview:_logoImageView];

        self.linelayer = [[CALayer alloc]init];

        self.linelayer.frame = CGRectMake((_logoImageView.frame.size.width-200)/2, 10, 200, 2);

self.linelayer.backgroundColor = [UIColorredColor].CGColor;

        [_logoImageView.layeraddSublayer:self.linelayer];

    }

-(void)openAction

{

    [_devicelockForConfiguration:nil];

if (!_isLightOn)

    {

        [_devicesetTorchMode:AVCaptureTorchModeOn];

        _isLightOn = YES;

    }

    else

    {

        [_devicesetTorchMode:AVCaptureTorchModeOff];

        _isLightOn = NO;

    }

    [_deviceunlockForConfiguration];

}


#pragma mark -AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput

didOutputMetadataObjects:(NSArray *)metadataObjects

       fromConnection:(AVCaptureConnection *)connection

{

    NSString *stringValue;

    if ([metadataObjects count] >0)

    {

        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];

        stringValue = metadataObject.stringValue;

    }

    [_sessionstopRunning];

    if ( [self.delegate respondsToSelector:@selector(qrScanViewController:didFinishQRScanWithResult:)] )

    {

        [self.delegateqrScanViewController:selfdidFinishQRScanWithResult:stringValue];

    }

}