iOS中如何生成二维码

首先导入框架

然后通过滤镜CIFiter生成二维码

#import <CoreImage/CoreImage.h>

/**

 *  生成二维码

 */

- (void)creat

{

    //1.创建过滤对象

    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

    

    //2.设置相关属性

    [filter setDefaults];

    

    //3.设置输入数据

    NSString *inputData = @"http://www.baidu.com";

    NSData *data = [inputData dataUsingEncoding:NSUTF8StringEncoding];

    [filter setValue:data forKeyPath:@"inputMessage"];

    

    //4.获取输出结果

    CIImage *outputImage = [filter outputImage];

    

    //5.显示二维码

    //    self.imageView.image = [UIImage imageWithCIImage:outputImage];

    self.imageView.image = [UIImage createNonInterpolatedUIImageFormCIImage:outputImage withSize:200 ];

 

}

 

#import <AVFoundation/AVFoundation.h>

 

@property (nonatomic, weak) AVCaptureSession *session;

@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;

/**

 *  扫描二维码

 */

- (void)scan

{

    //1.创建捕捉会话

    AVCaptureSession *session = [[AVCaptureSession alloc] init];

    

    // 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:@[AVMetadataObjectTypeQRCode]];

    

    // 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(@"%@", object.stringValue);

        

        // 停止扫描

        [self.session stopRunning];

        

        // 将预览图层移除

        [self.layer removeFromSuperlayer];

    } else {

        NSLog(@"没有扫描到数据");

    }

}

 

posted @ 2016-04-11 22:34  Huster2009  阅读(212)  评论(0编辑  收藏  举报