如今在国内无论走到哪里,只要是涉及支付的方面都可以使用支付宝或微信扫个二维码进行付款。现在二维码随处可见,二维码支付,二维码点餐,二维码坐公交,二维码做地铁,广告宣传页上, 电视台节目上等等。另外连乞丐都用上二维码了,你没带钱没关系,扫码给乞丐。二维码公交,地铁,点餐,支付已经是一种潮流,我们必须顺应潮流。IOS怎么实现扫描二维码功能呢?
直接复制代码粘贴一下即可使用,贴上@2x @3x图片,另外权限别忘了
//
// QRViewController.m
// TYSmartTimerKit
//
// Created by Eifi on 2019/7/3.
// Copyright © 2019 sz_bofu. All rights reserved.
//
#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate, AVCaptureVideoDataOutputSampleBufferDelegate>{
NSTimer *_timer;
BOOL upOrDown;
int num;
}
@property (strong, nonatomic) AVCaptureDevice * device;
@property (strong, nonatomic) AVCaptureDeviceInput * input;
@property (strong, nonatomic) AVCaptureMetadataOutput * output;
@property (strong, nonatomic) AVCaptureSession *session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer * preview;
@property (strong, nonatomic) UIImageView *imageView;
@property (retain, nonatomic) UIImageView *line;
@property (nonatomic, strong) NSString *identifier;
@end
@implementation QRViewController
- (AVCaptureDevice *)device{
if (_device == nil) {
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
return _device;
}
- (AVCaptureDeviceInput *)input{
if (_input == nil) {
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
}
return _input;
}
- (AVCaptureMetadataOutput *)output{
if (_output == nil) {
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//限制扫描区域(上下左右)
[_output setRectOfInterest:[self rectOfInterestByScanViewRect:_imageView.frame]];
}
return _output;
}
- (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
CGFloat width = CGRectGetWidth(self.view.frame);
CGFloat height = CGRectGetHeight(self.view.frame);
CGFloat x = (height - CGRectGetHeight(rect)) / 2 / height;
CGFloat y = (width - CGRectGetWidth(rect)) / 2 / width;
CGFloat w = CGRectGetHeight(rect) / height;
CGFloat h = CGRectGetWidth(rect) / width;
return CGRectMake(x, y, w, h);
}
- (AVCaptureSession *)session{
if (_session == nil) {
//session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input]) {
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output]) {
[_session addOutput:self.output];
}
}
return _session;
}
- (AVCaptureVideoPreviewLayer *)preview{
if (_preview == nil) {
_preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
}
return _preview;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if (![TYUtils isEnableCamera]) {
[UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"", @"") message:NSLocalizedString(@"请在iphone的“设置-隐私-相机”选项中,允许定时宝访问你的相机", @"") cancelButtonTitle:NSLocalizedString(@"取消", @"") otherButtonTitles:@[NSLocalizedString(@"前往", @"")] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == 0) {
[tp_topMostViewController().navigationController popViewControllerAnimated:YES];
}
else {
NSURL *prefs = [TYUtils prefsUrlWithQuery:@{@"root":@"General"}];
[[UIApplication sharedApplication] openURL:prefs];
}
}];
}
else {
[self initView];
}
}
- (void)initView {
if (self.device == nil) {
[UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"未检测到摄像头!", @"") message:@"" cancelButtonTitle:NSLocalizedString(@"确定", @"") otherButtonTitles:@[] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
[self.navigationController popViewControllerAnimated:YES];
}];
return;
}
[self addTimer];
[self addImageView];
[self scanSetup];
}
//添加扫描框
- (void)addImageView{
_imageView = [[UIImageView alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-(self.view.centerX+30))/2, (APP_SCREEN_HEIGHT-(self.view.centerX + 30))/2, self.view.centerX + 30, self.view.centerX + 30)];
//显示扫描框
_imageView.image = [UIImage imageNamed:@"ty_qrcode_bg"];
[self.view addSubview:_imageView];
_line = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(_imageView.frame)+5, CGRectGetMinY(_imageView.frame)+5, CGRectGetWidth(_imageView.frame), 3)];
_line.image = [UIImage imageNamed:@"ty_qrcode_line"];
[self.view addSubview:_line];
UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
[lable setText:@"将二维码放入框内,自动识别"];
lable.textAlignment = NSTextAlignmentCenter;
lable.textColor = [UIColor whiteColor];
lable.font = [UIFont systemFontOfSize:14];
lable.center = CGPointMake(_imageView.center.x , _imageView.center.y+ (self.view.centerX + 30)/2 + 30);
[self.view addSubview:lable];
}
//初始化扫描配置
- (void)scanSetup{
self.preview.frame = self.view.bounds;
self.preview.videoGravity = AVLayerVideoGravityResize;
[self.view.layer insertSublayer:self.preview atIndex:0];
[self.output setMetadataObjectTypes:@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode]];
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
[self.session startRunning];
}
- (void)viewDidDisappear:(BOOL)animated {
[self.session stopRunning];
[_timer setFireDate:[NSDate distantFuture]];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if ([metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
if ([metadataObject isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
NSString *stringValue = [metadataObject stringValue];
if (stringValue != nil) {
[self.session stopRunning];
NSLog(@"%@",stringValue);
}
}
}
}
- (void)addTimer{
_timer = [NSTimer scheduledTimerWithTimeInterval:0.008 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
}
//控制扫描线上下滚动
- (void)timerMethod{
if (upOrDown == NO) {
num ++;
_line.frame = CGRectMake(CGRectGetMinX(_imageView.frame)+5, CGRectGetMinY(_imageView.frame)+5+num, CGRectGetWidth(_imageView.frame)-10, 3);
if (num == (int)(CGRectGetHeight(_imageView.frame)-10)) {
upOrDown = YES;
}
}
else{
num --;
_line.frame = CGRectMake(CGRectGetMinX(_imageView.frame)+5, CGRectGetMinY(_imageView.frame)+5+num, CGRectGetWidth(_imageView.frame)-10, 3);
if (num == 0) {
upOrDown = NO;
}
}
}
//暂定扫描
- (void)stopScan{
[self.session stopRunning];
[_timer setFireDate:[NSDate distantFuture]];
_line.hidden = YES;
}
- (void)starScan{
[self.session startRunning];
[_timer setFireDate:[NSDate distantPast]];
_line.hidden = NO;
}
@end