基础功能,具体细节处理,需要再添加;
授权
二维码扫描需要拍照功能,
AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (authorizationStatus) {
case AVAuthorizationStatusNotDetermined: {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler: ^(BOOL granted) {
if (granted) {
[self startCapture];
} else {
NSLog(@"%@", @"访问受限");
}
}];
break;
}
case AVAuthorizationStatusAuthorized: {
[self startCapture];
break;
}
case AVAuthorizationStatusRestricted:
case AVAuthorizationStatusDenied: {
NSLog(@"%@", @"访问受限");
break;
}
default: {
break;
}
}
开启拍照扫描
- (void)startCapture {
dispatch_async(dispatch_get_main_queue(), ^{
AVCaptureSession *session = [[AVCaptureSession alloc] init];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (deviceInput) {
[session addInput:deviceInput];
AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:metadataOutput]; // 这行代码要在设置 metadataObjectTypes 前
metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
previewLayer.frame = self.view.frame;
[self.view.layer insertSublayer:previewLayer atIndex:0];
CGRect rect = CGRectMake(CZScanLeftAndRightPadding, CZScanTopPadding, CGRectGetWidth([UIScreen mainScreen].bounds) - 2 * CZScanLeftAndRightPadding, CGRectGetWidth([UIScreen mainScreen].bounds) - 2 * CZScanLeftAndRightPadding);
[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification
object:nil
queue:[NSOperationQueue currentQueue]
usingBlock: ^(NSNotification *_Nonnull note) {
metadataOutput.rectOfInterest = [previewLayer metadataOutputRectOfInterestForRect:rect]; // 如果不设置,整个屏幕都可以扫
}];
QRScanView *scanView = [[QRScanView alloc] initWithScanRect:rect];
[self.view addSubview:scanView];
[session startRunning];
self.messageLabel.hidden = YES;
} else {
NSLog(@"%@", error);
}
});
}
扫描成果
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
if ([metadataObject.type isEqualToString:AVMetadataObjectTypeQRCode]) { // 成功后系统不会停止扫描,可以用一个变量来控制。
if (self.scanComplete) {
self.scanComplete(metadataObject.stringValue);
}
NSLog(@"提示扫描成功没,1秒后返回,不然刷就回去了");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:YES];
});
}
}
iOS8 识别图中二维码
给 image 加个 类别就可以用了
- (NSString *)scanQRCodeFromImage {
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy:CIDetectorAccuracyHigh }];
CIImage *image = [[CIImage alloc] initWithImage:self];
NSArray *features = [detector featuresInImage:image];
CIQRCodeFeature *feature = [features firstObject];
if (feature) {
return feature.messageString;
} else {
return @"没有二维码";
}
}
生成二维码
同样 拓展类就行了,可能生成的图片比较糊,那么就放大倍数大一点就好了;
+ (UIImage *)createQRImageWithContent:(NSString *)content scale:(CGFloat)scale {
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding]; // NSISOLatin1StringEncoding 编码
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
[filter setValue:@"M" forKey:@"inputCorrectionLevel"];// L: 7% M: 15% Q: 25% H: 30%
CIImage *outputImage = filter.outputImage;
CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale); // scale 为放大倍数
CIImage *transformImage = [outputImage imageByApplyingTransform:transform];
// 保存
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef imageRef = [context createCGImage:transformImage fromRect:transformImage.extent];
UIImage *qrCodeImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return qrCodeImage;
}