Created
September 21, 2015 16:45
-
-
Save snej/6440a2e041222018cc7c to your computer and use it in GitHub Desktop.
Snippet showing how to capture QR codes from the device camera on iOS or Mac OS X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL) startCapture: (NSError**)outError { | |
if (!_session) { | |
_session = [[AVCaptureSession alloc] init]; | |
AVCaptureDevice* video = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo]; | |
if (!video) | |
return [self failWithMessage: @"No video camera available" error: outError]; | |
AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice: video | |
error: outError]; | |
if (!input) | |
return [self failWithMessage: @"Couldn't acquire input device" error: outError]; | |
[_session addInput: input]; | |
AVCaptureVideoDataOutput* output = [[AVCaptureVideoDataOutput alloc] init]; | |
output.alwaysDiscardsLateVideoFrames = YES; | |
[output setSampleBufferDelegate: self queue: dispatch_get_main_queue()]; | |
[_session addOutput: output]; | |
NSLog(@"Starting video capture..."); | |
[[NSNotificationCenter defaultCenter] addObserver: self | |
selector: @selector(sessionNotification:) | |
name: nil // all notifications | |
object: _session]; | |
[_session startRunning]; | |
} | |
if (!_qrDetector) { | |
_qrDetector = [CIDetector detectorOfType: CIDetectorTypeQRCode | |
context: nil | |
options: nil]; | |
} | |
return YES; | |
} | |
- (void)captureOutput:(AVCaptureOutput *)captureOutput | |
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer | |
fromConnection:(AVCaptureConnection *)connection | |
{ | |
CVImageBufferRef imageBuf = CMSampleBufferGetImageBuffer(sampleBuffer); | |
CIImage* frame = [CIImage imageWithCVImageBuffer: imageBuf]; | |
CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); | |
if (time - _lastScanTime >= kMinScanInterval) { | |
_lastScanTime = time; | |
self.scannedFeature = (CIQRCodeFeature*)[_qrDetector featuresInImage: frame].firstObject; | |
} | |
self.currentFrame = frame; | |
NSString* message = [self.scannedFeature.messageString copy]; | |
if (message && ![message isEqualToString: _scannedString]) { | |
self.scannedString = message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment