iOS-仿微信扫一扫、长按识别二维码,以及一句话生成二维码

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 里面设置访问权限

Paste_Image.png

在解析获取捕捉到的信息后会在代理 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的修改

Paste_Image.png

在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
Paste_Image.png
Paste_Image.png

好了,这样介绍完了,上面的几个类就可以实现功能。

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:@"http://www.jianshu.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。相互学习。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容