扫描二维码控件的封装iOS实现

扫描二维码效果

源码:https://github.com/YouXianMing/Animations

//
// QRCodeView.h
// QRCode
//
// Created by YouXianMing on 16/7/7.
// Copyright © 2016年 XianMing You. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class QRCodeView;

@protocol QRCodeViewDelegate <NSObject>

@optional

/**
 * 获取QR的扫描结果
 *
 * @param codeView QRCodeView实体对象
 * @param codeString 扫描字符串
 */
- (void)QRCodeView:(QRCodeView *)codeView codeString:(NSString *)codeString;

@end

@interface QRCodeView : UIView

/**
 * 代理
 */
@property (nonatomic, weak) id <QRCodeViewDelegate> delegate;

/**
 * 灯的状态,默认为关闭
 */
@property (nonatomic) AVCaptureTorchMode torchMode;

/**
 * 敏感区域,如果不设置,则为全部扫描区域
 */
@property (nonatomic) CGRect interestArea;

/**
 * 你用来添加自定义控件的view,尺寸与当前初始化的view一致
 */
@property (nonatomic, strong) UIView *contentView;

/**
 * 正在运行当中
 */
@property (nonatomic, readonly) BOOL isRunning;

/**
 * 开始扫描
 *
 * @return 如果成功,则返回YES,否则返回NO
 */
- (BOOL)start;

/**
 * 结束扫描
 */
- (void)stop;

@end
//
// QRCodeView.m
// QRCode
//
// Created by YouXianMing on 16/7/7.
// Copyright © 2016年 XianMing You. All rights reserved.
//

#import "QRCodeView.h"

@interface QRCodeView () <AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic) BOOL         isRunning;
@property (nonatomic, strong) UIView      *videoView;

@property (nonatomic, strong) AVCaptureDeviceInput  *deviceInput;
@property (nonatomic, strong) AVCaptureDevice    *captureDevice;
@property (nonatomic, strong) AVCaptureSession   *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, strong) AVCaptureMetadataOutput  *captureMetadataOutput;

@end

@implementation QRCodeView

- (instancetype)initWithFrame:(CGRect)frame {

 if (self = [super initWithFrame:frame]) {

  self.videoView = [[UIView alloc] initWithFrame:self.bounds];
  [self addSubview:self.videoView];

  self.contentView = [[UIView alloc] initWithFrame:self.bounds];
  [self addSubview:self.contentView];

  self.captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

  _torchMode = AVCaptureTorchModeOff;

  [self addNotificationCenter];
 }

 return self;
}

#pragma mark - NSNotificationCenter related.

- (void)addNotificationCenter {

 [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(notificationCenterEvent:)
             name:AVCaptureInputPortFormatDescriptionDidChangeNotification
            object:nil];
}

- (void)removeNotificationCenter {

 [[NSNotificationCenter defaultCenter] removeObserver:self
             name:AVCaptureInputPortFormatDescriptionDidChangeNotification
             object:nil];
}

- (void)notificationCenterEvent:(NSNotification *)sender {

 if (self.interestArea.size.width && self.interestArea.size.height) {

  self.captureMetadataOutput.rectOfInterest = [self.videoPreviewLayer metadataOutputRectOfInterestForRect:self.interestArea];

 } else {

  self.captureMetadataOutput.rectOfInterest = CGRectMake(0, 0, 1, 1);
 }
}

#pragma mark - Start & Stop.

- (BOOL)start {

 // 初始化输入流
 BOOL  result = NO;
 NSError *error = nil;
 self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:&error];
 if (self.deviceInput == nil) {

  NSLog(@"%@", error);
  return result;
 }

 // 创建会话
 self.captureSession = [[AVCaptureSession alloc] init];

 // 添加输入流
 [self.captureSession addInput:self.deviceInput];

 // 初始化输出流
 self.captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];

 // 添加输出流
 [self.captureSession addOutput:self.captureMetadataOutput];

 // 创建queue.
 [self.captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_queue_create(nil, nil)];
 self.captureMetadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];

 // 创建输出对象
 self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
 self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
 self.videoPreviewLayer.frame = self.contentView.bounds;
 [self.videoView.layer addSublayer:self.videoPreviewLayer];

 // 开始
 [self.captureSession startRunning];
 self.isRunning = YES;
 result   = YES;

 return result;
}

- (void)stop {

 [self.captureSession stopRunning];
 self.isRunning  = NO;
 self.captureSession = nil;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
  fromConnection:(AVCaptureConnection *)connection {

 if (metadataObjects.count > 0) {

  AVMetadataMachineReadableCodeObject *metadata = metadataObjects.firstObject;
  NSString       *result = nil;

  if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {

   result = metadata.stringValue;

   if (_delegate && [_delegate respondsToSelector:@selector(QRCodeView:codeString:)]) {

    [_delegate QRCodeView:self codeString:result];
   }
  }
 }
}

#pragma mark - Setter & Getter.

- (void)setTorchMode:(AVCaptureTorchMode)torchMode {

 _torchMode = torchMode;

 if (_deviceInput && [self.captureDevice hasTorch]) {

  [self.captureDevice lockForConfiguration:nil];
  [self.captureDevice setTorchMode:torchMode];
  [self.captureDevice unlockForConfiguration];
 }
}

#pragma mark - System method.

- (void)dealloc {

 [self stop];
 [self removeNotificationCenter];
}

@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • ios swift3.0实现二维码扫描、生成、识别示例代码

    基于swift3.0 1.扫描二维码 设置扫描会话,图层和输入输出 //设置捕捉设备 let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { //设置设备输入输出 let input = try AVCaptureDeviceInput(device: device) let output = AVCaptureMetadataOutput() output.setMetadataObjec

  • ios原生二维码扫描

    做iOS的二维码扫描,有两个第三方库可以选择,ZBar和ZXing.今天要介绍的是iOS7.0后AVFoundation框架提供的原生二维码扫描. 首先需要添加AVFoundation.framework框架到你工程中build phase的"Link Binary With Libraries"之下,然后就可以开始了. 一.做好准备工作,搭建UI UI效果如图 IBOutlet.IBAction如下: @property (weak, nonatomic) IBOutlet UIVi

  • iOS实现二维码的扫描功能

    直接上代码,就不多废话了 // // ViewController.m // QRCode // // Created by chenchen on 15/7/30. // Copyright (c) 2015年 BSY. All rights reserved. // #import <AVFoundation/AVFoundation.h> #import "ViewController.h" @interface ViewController ()<AVCapt

  • iOS二维码的生成和扫描

    本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 属性 @property (strong,nonatomic)AVCaptureDevice * device; @property (strong,nonatomic)AVCaptureDeviceInput * input; @property (strong,nonatomic)AVCaptureMetadataOutput * output; @property (strong,nonatomic)AV

  • IOS应用内跳转系统设置相关界面的方法

    在iOS开发中,有时会有跳转系统设置界面的需求,例如提示用户打开蓝牙或者WIFI,提醒用户打开推送或者位置权限等.在iOS6之后,第三方应用需要跳转系统设置界面,需要在URL type中添加一个prefs值,如下图: 跳转系统设置根目录中的项目使用如下的方法: _array = @[ @{@"系统设置":@"prefs:root=INTERNET_TETHERING"}, @{@"WIFI设置":@"prefs:root=WIFI&qu

  • iOS应用开发中实现页面跳转的简单方法笔记

    作为新手写的笔记,方便自己记忆: 从android转过来iOS的,对于页面的跳转,找了很多资料,现在记录一下页面跳转的方法. 1.用navigationController 2.直接跳(刚刚在网上找到的,不太熟,有错莫怪) 1.建一个RootViewController,在delegate.h 复制代码 代码如下: @property (strong, nonatomic) UIViewController *viewController; @property (strong, nonatomi

  • iOS应用程序之间的几种跳转情况详解

    前言 在iOS开发的过程中,我们经常会遇到比如需要从一个应用程序A跳转到另一个应用程序B的场景.这就需要我们掌握iOS应用程序之间的相互跳转知识.下面我们就常用到的几种跳转情况进行介绍. 一.跳转到另一个程序的主界面 每个程序都该有一个对应的Scheme,以确定对应的url 一个程序要跳转到(打开)另外一个程序,需要将另外一个程序的Scheme添加到自己的应用程序白名单中(在info.plist中配置:LSApplicationQueriesSchemes,类型为数组,在数组中添加相应的Sche

  • IOS笔记061之二维码的生成和扫描

    如今二维码随处可见,无论是实物商品还是各种礼券都少不了二维码的身影.而手机等移动设备又成为二维码的一个很好的应用平台,不管是生成二维码还是扫码二维码.本篇文章从生成二维码.扫描二维码展开分析,通过内容分析二维码用起来也很easy了. 首先说下生成二维码 二维码可以存放纯文本.名片或者URL 其次生成二维码的步骤: 导入CoreImage框架 再次通过滤镜CIFilter生成二维码 1.创建过滤器 2.恢复滤镜的默认属性 3.设置内容 4.获取输出文件 5.显示二维码 代码实现 CoreImage

  • iOS 二维码扫描和应用跳转

    前面我们已经调到过怎么制作二维码,在我们能够生成二维码之后,如何对二维码进行扫描呢? 在iOS7之前,大部分应用中使用的二维码扫描是第三方的扫描框架,例如ZXing或者ZBar.使用时集成麻烦,出错也不方便调试.在iOS7之后,苹果自身提供了二维码的扫描功能,从效率上来说,原生的二维码远高于这些第三方框架.本文讲解如何使用原生框架实现二维码扫描功能,并且进行扫描后的项目跳转. 扫描相关类 二维码扫描需要获取摄像头并读取照片信息,因此我们需要导入系统的AVFoundation框架,创建视频会话.我

  • iOS 条码及二维码扫描(从相册中读取条形码/二维码)及扫码过程中遇到的坑

    文章重点介绍如何解决,从手机相册中读取条形码和二维码的问题 1.扫码. 网上有特别的关于iOS扫码的代码和示例,其中扫码主要使用的是自带的AVFoundation类.这里就不细说了,要注意的是如何设置扫描区域,识别区域(这个值是按比例0~1设置,而且X.Y要调换位置,width.height调换位置) <span style="font-size:14px;">//创建输出流 AVCaptureMetadataOutput * output = [[AVCaptureMet

随机推荐