項(xiàng)目地址:https://github.com/tujinqiu/KTQRCode
1、二維碼掃描
- (void)startScan
{
[self.popView startAnimateScanBar];
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
NSParameterAssert(input);
self.captureSession = [[AVCaptureSession alloc] init];
[self.captureSession addInput:input];
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[self.captureSession addOutput:output];
dispatch_queue_t queue = dispatch_queue_create("KTScanViewControllerScanQueue", DISPATCH_QUEUE_SERIAL);
[output setMetadataObjectsDelegate:self queue:queue];
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
CGSize size = [UIScreen mainScreen].bounds.size;
CGRect outputFrame = self.popView.scanFrame;
[output setRectOfInterest:CGRectMake(outputFrame.origin.y / size.height, outputFrame.origin.x / size.width, outputFrame.size.height / size.height, outputFrame.size.width / size.width)];
[self.previewLayerView configWithSession:self.captureSession];
[self.captureSession startRunning];
}
#pragma mark -- AVCaptureMetadataOutputObjectsDelegate --
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if ([metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *obj = [metadataObjects firstObject];
NSString *result = nil;
if ([[obj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
result = obj.stringValue;
}
dispatch_sync(dispatch_get_main_queue(), ^{
[self stopScan];
KTQRCodeController *controller = (KTQRCodeController *)self.navigationController;
if (result && [controller.QRCodeDelegate respondsToSelector:@selector(QRCodeController:didScanResult:)]) {
[controller.QRCodeDelegate QRCodeController:controller didScanResult:result];
}
});
}
}
2悲柱、從相冊識別二維碼
- (void)readQRCodeFromImage:(UIImage *)image result:(void (^)(NSString *resultString))result
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:CIDetectorAccuracyHigh, CIDetectorAccuracy, nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:options];
NSArray *features = [detector featuresInImage:ciImage];
NSString *str = nil;
if (features.count > 0) {
CIQRCodeFeature *feature = [features firstObject];
str = feature.messageString;
}
if (result) {
dispatch_async(dispatch_get_main_queue(), ^{
result(str);
});
}
});
}