iOS-仿微信扫一扫、长按识别二维码,以及一句话生成二维码
1、二维码简介
在iOS中二维码的实质是一个字符串,一般用于制作名片,手机电商购物链家、微信扫一扫,微信支付,QQ加好友,以及移动支付等。其中用的最广的当然是大家熟知的支付宝,微信和QQ了。既然二维码用途这么广,很多APP里面都或多或少有二维码的存在,那么下面就扫一扫二维码,长按识别二维码,以及生成二维码从无到有的过程,和遇到的坑分享给大家。
2、进入主题
在一定的程度之后,相信大家都有封装的思想,那么本文有几个分装介绍给大家:
JWDQRCodeViewController.h 扫一扫控制器分装
JWDPreView.h 扫一扫动画界面封装
JWDCreatQRCodeView.h 生成二维码封装
下面就这三个类进行介绍
3、JWDQRCodeViewController 扫一扫控制器分装
JWDQRCodeViewController.h
.h 没什么可说的,给外界的接口
#import <UIKit/UIKit.h>
@interface JWDQRCodeViewController : UIViewController
- (instancetype)initWithFrame:(CGRect)frame;
@end
JWDQRCodeViewController.m
导入相应的头文件,必须的变量
其中SafariServices/SafariServices.h框架用于url跳转控制器,是iOS9之后的新特性,可以方便打开相应的网页界面。
#import "JWDQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "JWDPreView.h"
#import <SafariServices/SafariServices.h>
@interface JWDQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic, strong)AVCaptureDeviceInput *deviceInput;//!< 摄像头输入
@property(nonatomic, strong)AVCaptureMetadataOutput *metadataOutput;//!< 输出
@property(nonatomic, strong)AVCaptureSession *session;//!< 会话
@property(nonatomic, strong)AVCaptureVideoPreviewLayer *previewLayer;//!< 预览
@property(nonatomic, strong)JWDPreView *preView;//!< <#value#>
@end
@implementation JWDQRCodeViewController
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super init];
if (self) {
self.view.frame = frame;
[self initUiConfig];
}
return self;
}
-(void)initUiConfig {
// 默认为后置摄像头
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
self.deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:NULL];
// 解析输入的数据
self.metadataOutput = [[AVCaptureMetadataOutput alloc] init];
[self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 会话
self.session = [[AVCaptureSession alloc] init];
if ([self.session canAddInput:self.deviceInput]){
[self.session addInput:self.deviceInput];
}
if([self.session canAddOutput:self.metadataOutput]){
[self.session addOutput:self.metadataOutput];
}
// 设置数据采集质量
self.session.sessionPreset = AVCaptureSessionPresetHigh;
// 设置需要解析的数据类型,二维码
self.metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
JWDPreView *preView = [[JWDPreView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
self.preView = preView;
[self.view addSubview:preView];
preView.session = self.session;
preView.backPreView = ^(JWDPreView *backPreView){
[self.session stopRunning];
[self dismissViewControllerAnimated:YES completion:nil];
// 销毁定时器
if (backPreView.timer){
[backPreView.timer invalidate];
backPreView.timer = nil;
}
};
[self.session startRunning];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:obj.stringValue]];
[self presentViewController:safariVC animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
上面建立采集二维码的过滤器,和基本的输入和输出的建立,链接输入和输出的会话建立,以及开启和适当的时候关闭会话的处理。
切记这里要使用摄像头,所以要者info.plist 里面设置访问权限
在解析获取捕捉到的信息后会在代理 AVCaptureMetadataOutputObjectsDelegate的下面方法里面获取信息
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:obj.stringValue]];
[self presentViewController:safariVC animated:YES completion:nil];
}
}
获取到相应的数据后可以在这里面做一些业务逻辑,本人在这里就用到SFSafariViewController控制器来代开网页
好了下面介绍扫描界面
4.JWDPreView 扫一扫动画界面封装
JWDPreView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class JWDPreView;
typedef void(^backPreView) (JWDPreView *preView);
@interface JWDPreView : UIView
- (instancetype)initWithFrame:(CGRect)frame;
@property(nonatomic, strong)AVCaptureSession *session;//!< 渲染会话层
@property (nonatomic, copy) backPreView backPreView;//!< 返回按钮回调
@property(nonatomic, strong)NSTimer *timer;//!< <#value#>
@end
JWDPreView.m
#import "JWDPreView.h"
@interface JWDPreView ()
{
UIImageView *_imageView;
UIImageView *_lineImageView;
UIButton *_backBtn;
}
@end
@implementation JWDPreView
// 修改当前View 的图层类别
+(Class)layerClass {
return [AVCaptureVideoPreviewLayer class];
}
-(void)setSession:(AVCaptureSession *)session {
_session = session;
AVCaptureVideoPreviewLayer *layer = (AVCaptureVideoPreviewLayer *)self.layer;
layer.session = session;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initUiConfig];
}
return self;
}
- (void)initUiConfig {
_backBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 50, 40, 20)];
[_backBtn setTitle:@"返回" forState:UIControlStateNormal];
[_backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_backBtn addTarget:self action:@selector(backButtonDid) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_backBtn];
_imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pick_bg.png"]];
_imageView.frame = CGRectMake(self.bounds.size.width * 0.5 - 140, self.bounds.size.height * 0.5 - 140, 280, 280);
[self addSubview:_imageView];
_lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 220, 2)];
_lineImageView.image = [UIImage imageNamed:@"line.png"];
[_imageView addSubview:_lineImageView];
_timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(animation) userInfo:nil repeats:YES];
}
- (void)animation
{
[UIView animateWithDuration:2.8 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
_lineImageView.frame = CGRectMake(30, 260, 220, 2);
} completion:^(BOOL finished) {
_lineImageView.frame = CGRectMake(30, 10, 220, 2);
}];
}
- (void)backButtonDid {
if (self.backPreView){
self.backPreView(self);
}
}
@end
在.m中一个重点就是 扫一扫界面浏览layer的修改
在UIView中默认的 为 [CALayer class]而这不是二维码扫描所需的layer,所以修改。这样强转后的layer才有session的会话设置
// 修改当前View 的图层类别
+(Class)layerClass {
return [AVCaptureVideoPreviewLayer class];
}
-(void)setSession:(AVCaptureSession *)session {
_session = session;
AVCaptureVideoPreviewLayer *layer = (AVCaptureVideoPreviewLayer *)self.layer;
layer.session = session;
}
5.JWDCreatQRCodeView 生成二维码封装
JWDCreatQRCodeView.h
一句话生成二维码的接口
#import <UIKit/UIKit.h>
@interface JWDQRCodeViewController : UIViewController
- (instancetype)initWithFrame:(CGRect)frame;
@end
JWDCreatQRCodeView.m
#import "JWDQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "JWDPreView.h"
#import <SafariServices/SafariServices.h>
@interface JWDQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic, strong)AVCaptureDeviceInput *deviceInput;//!< 摄像头输入
@property(nonatomic, strong)AVCaptureMetadataOutput *metadataOutput;//!< 输出
@property(nonatomic, strong)AVCaptureSession *session;//!< 会话
@property(nonatomic, strong)AVCaptureVideoPreviewLayer *previewLayer;//!< 预览
@property(nonatomic, strong)JWDPreView *preView;//!< <#value#>
@end
@implementation JWDQRCodeViewController
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super init];
if (self) {
self.view.frame = frame;
[self initUiConfig];
}
return self;
}
-(void)initUiConfig {
// 默认为后置摄像头
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
self.deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:NULL];
// 解析输入的数据
self.metadataOutput = [[AVCaptureMetadataOutput alloc] init];
[self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 会话
self.session = [[AVCaptureSession alloc] init];
if ([self.session canAddInput:self.deviceInput]){
[self.session addInput:self.deviceInput];
}
if([self.session canAddOutput:self.metadataOutput]){
[self.session addOutput:self.metadataOutput];
}
// 设置数据采集质量
self.session.sessionPreset = AVCaptureSessionPresetHigh;
// 设置需要解析的数据类型,二维码
self.metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
JWDPreView *preView = [[JWDPreView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
self.preView = preView;
[self.view addSubview:preView];
preView.session = self.session;
preView.backPreView = ^(JWDPreView *backPreView){
[self.session stopRunning];
[self dismissViewControllerAnimated:YES completion:nil];
// 销毁定时器
if (backPreView.timer){
[backPreView.timer invalidate];
backPreView.timer = nil;
}
};
[self.session startRunning];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:obj.stringValue]];
[self presentViewController:safariVC animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
好了,这样介绍完了,上面的几个类就可以实现功能。
6.下面介绍
ViewController继承基本的全部功能
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "JWDPreView.h"
#import <SafariServices/SafariServices.h>
#import "JWDQRCodeViewController.h"
#import "JWDCreatQRCodeView.h"
@interface ViewController ()
@property(nonatomic, strong)UIButton *code;//!< <#value#>
@property(nonatomic, strong)UIButton *code1;//!< <#value#>
@property(nonatomic, strong)JWDCreatQRCodeView *creatQRCodeView;//!< <#value#>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat X = (self.view.frame.size.width - 2*100)/3.0;
_code = [[UIButton alloc] initWithFrame:CGRectMake(X, 100, 100, 60)];
_code.backgroundColor = [UIColor yellowColor];
[_code setTitle:@"扫一扫" forState:UIControlStateNormal];
[_code setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_code addTarget:self action:@selector(codeDidClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_code];
_code1 = [[UIButton alloc] initWithFrame:CGRectMake(2*X + 100, 100, 100, 60)];
_code1.backgroundColor = [UIColor yellowColor];
[_code1 setTitle:@"生成二维码" forState:UIControlStateNormal];
[_code1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_code1 addTarget:self action:@selector(code1DidClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_code1];
}
- (void)codeDidClick {
JWDQRCodeViewController *QRCodeVC = [[JWDQRCodeViewController alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self presentViewController:QRCodeVC animated:YES completion:nil];
}
- (void)code1DidClick {
UIView *qrCodeView = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width-200)*0.5, 250, 200, 220)];
[self.view addSubview:qrCodeView];
JWDCreatQRCodeView *creatQRCodeView = [[JWDCreatQRCodeView alloc] initWithFrame:CGRectMake(0, 0, 200, 200) withQRCodeString:@"//www.greatytc.com/users/5b9953c3d3ad/latest_articles" withQRCodeCenterImage:@"me"];
self.creatQRCodeView = creatQRCodeView;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 200, 20)];
label.text = @"长按识别二维码,跳转网页";
label.font = [UIFont systemFontOfSize:12];
label.textAlignment = NSTextAlignmentCenter;
[qrCodeView addSubview:label];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressDid)];
creatQRCodeView.userInteractionEnabled = YES;
[creatQRCodeView addGestureRecognizer:longPress];
[qrCodeView addSubview:creatQRCodeView];
}
- (void)longPressDid{
// 0.创建上下文
CIContext *context = [[CIContext alloc] init];
// 1.创建一个探测器
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
// 2.直接开始识别图片,获取图片特征
CIImage *imageCI = [[CIImage alloc] initWithImage:self.creatQRCodeView.image];
NSArray<CIFeature *> *features = [detector featuresInImage:imageCI];
CIQRCodeFeature *codef = (CIQRCodeFeature *)features.firstObject;
// 弹框
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"识别图中二维码" message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消");
}]];
__weak ViewController *weakSelf = self;
[alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:codef.messageString]];
[weakSelf presentViewController:safariVC animated:YES completion:nil];
}]];
[self presentViewController:alertC animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
完结,小小的一个demo,可能还有不完善的地方,当你发现了还请不吝赐教,谢谢。
最后奉上demo 地址 https://github.com/weidongjiang/JWD-QRCode
如果对你有用,解决了你的问题,得到了帮助,还请star。相互学习。