iOS中的二维码

一、二维码简介

从iOS7开始集成了二维码的生成和读取功能
此前被广泛使用的zbarsdk目前不支持64位处理器

二、生成二维码

1.生成二维码的步骤:

  • 导入CoreImage框架
  • 通过滤镜CIFilter生成二维码

2.二维码的内容(传统的条形码只能放数字):

  • 纯文本
  • 名片
  • URL

3.生成二维码的代码实现

#import "ViewController.h"
#import 

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 1.创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    NSString *dataString = @"http://www.520it.com";
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    
    // 5.显示二维码
    self.imageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
}

/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

@end

三、扫描二维码

1.读取二维码需要导入AVFoundation框架
2.利用摄像头识别二维码中的内容(模拟器不行)

  • 输入(摄像头)
  • 由会话将摄像头采集到的二维码图像转换成字符串数据
  • 输出(数据)
  • 由预览图层显示扫描场景

3.扫描二维码的代码

#import "ViewController.h"
#import 

@interface ViewController () 

@property (nonatomic, weak) AVCaptureSession *session;
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     
    // 1.创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2.添加输入设备(数据从摄像头输入)
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    
    // 3.1.设置输入元数据的类型(类型是二维码数据)
    [output setMetadataObjectTypes:[output availableMetadataObjectTypes]];
    
    // 4.添加扫描图层
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
    // 5.开始扫描
    [session startRunning];
}

#pragma mark - 实现output的回调方法
// 当扫描到数据时就会执行该方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
//        NSLog(@"%@--%zd", object.type,metadataObjects.count);
//        object.type
        
        // *****************
        NSLog(@"----------");
        NSLog(@"%@",object.stringValue);
        NSLog(@"----------");
        // 这段二维码的作用是是解决gbk乱码的作用
//        NSString *result=object.stringValue;//返回的扫描结果
//        NSData *data=[object.stringValue dataUsingEncoding:NSUTF8StringEncoding];
//        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//        NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];//如果中文是utf-8编码转gbk结果为空(还没搞明白)
//        if (retStr)//如果扫描中文乱码则需要处理,否则不处理
//        {
//            NSInteger max = [object.stringValue length];
//            char *nbytes = malloc(max + 1);
//            for ( int i = 0; i < max; i++)
//            {
//                unichar ch = [object.stringValue  characterAtIndex: i];
//                nbytes[i] = (char) ch;
//            }
//            nbytes[max] = '\0';
//            result=[NSString stringWithCString: nbytes
//                                      encoding: enc];
//            NSLog(@"成功的啦%@",result);
//        }
        // **************
        // 停止扫描
        [self.session stopRunning];
        
        // 将预览图层移除
        [self.layer removeFromSuperlayer];
    } else {
        NSLog(@"没有扫描到数据");
    }
}

@end

四、识别二维码

 CIImage* image;
    NSArray* array =[_QRCodeDector featuresInImage:image];

    for (CIFeature* feature in array) {
        if([feature isKindOfClass:[CIQRCodeFeature class]]) {
            CIQRCodeFeature* QRCodeFeature = (CIQRCodeFeature*)feature;
            [[[UIAlertView alloc] initWithTitle:@"二维码" message:QRCodeFeature.messageString delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
            return;
        }
    }

你可能感兴趣的:(iOS中的二维码)