二维码扫描识别的有名的第三方库有zbar,zxing,ios7以后iOS自带的AVFoundation框架可以实现二维码扫描识别的功能
扫码
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[self.navigationController popViewControllerAnimated:YES];
}
AVCaptureSession* session = [[AVCaptureSession alloc] init];
[session addInput:input];
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_queue_create("capture_queue", NULL)];
[session addOutput:output];
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
output.rectOfInterest =[_previewLayer metadataOutputRectOfInterestForRect:scanRect];
}];
识别二维码
- (void)scanImageQRCode:(NSDictionary*)info{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (!image) {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
CIQRCodeFeature *feature = (CIQRCodeFeature*)[[self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]] firstObject];
if (feature) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:feature.messageString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:@"无法识别二维码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
[self startScan];
}
生成二维码
NSData *data = [QRCodeText dataUsingEncoding:NSUTF8StringEncoding];
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
CIImage *ciImage = filter.outputImage;
CGFloat scale = CGRectGetWidth(self.QRCodeImage.bounds)/CGRectGetWidth(ciImage.extent);
CIImage *transformImage = [ciImage imageByApplyingTransform:CGAffineTransformMakeScale(scale ,scale)];
self.QRCodeImage.image = [[UIImage imageWithCIImage:transformImage] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
UIImageWriteToSavedPhotosAlbum(self.QRCodeImage.image, self, nil, NULL);