全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

iOS实现“摇一摇”与“扫一扫”功能示例代码

“摇一摇”功能的实现:

iPhone对 “摇一摇”有很好的支持,总体说来就两步:

在视图控制器中打开接受“摇一摇”的开关;

 - (void)viewDidLoad {
  // 设置允许摇一摇功能
  [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
  // 并让自己成为第一响应者
  [self becomeFirstResponder];
}

在“摇一摇”触发的制定的方法中实现需要实现的功能(”摇一摇“检测方法)。

// 摇一摇开始摇动 
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
  NSLog(@"开始摇动");
  //添加“摇一摇”动画
  [self addAnimations];
  //音效
  AudioServicesPlaySystemSound (soundID); 
  return; 
} 

// “摇一摇”取消摇动 
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
  NSLog(@"取消摇动"); 
  return; 
} 

// “摇一摇”摇动结束 
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
  if (event.subtype == UIEventSubtypeMotionShake) { // 判断是否是摇动结束 
    NSLog(@"摇动结束"); 
  } 
  return; 
} 

”摇一摇“的动画效果:

- (void)addAnimations {
  //音效
  AudioServicesPlaySystemSound (soundID);
  //让上面图片的上下移动
  CABasicAnimation *translation2 = [CABasicAnimation animationWithKeyPath:@"position"];
  translation2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  translation2.fromValue = [NSValue valueWithCGPoint:CGPointMake(160, 115)];
  translation2.toValue = [NSValue valueWithCGPoint:CGPointMake(160, 40)];
  translation2.duration = 0.4;
  translation2.repeatCount = 1;
  translation2.autoreverses = YES;

  //让下面的图片上下移动
  CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];
  translation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  translation.fromValue = [NSValue valueWithCGPoint:CGPointMake(160, 345)];
  translation.toValue = [NSValue valueWithCGPoint:CGPointMake(160, 420)];
  translation.duration = 0.4;
  translation.repeatCount = 1;
  translation.autoreverses = YES;

  [imgDown.layer addAnimation:translation forKey:@"translation"];
  [imgUp.layer addAnimation:translation2 forKey:@"translation2"];  
}

注意:在模拟器中运行时,可以通过「Hardware」-「Shake Gesture」来测试「摇一摇」功能。如下:

“扫一扫”功能的实现:

基于AVCaptureDevice做的二维码扫描器,基本步骤如下:

初始化相机,生成扫描器

 设置参数

 - (void)setupCamera {

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];

    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    _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];
    }

    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes = [NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil];

    dispatch_async(dispatch_get_main_queue(), ^{
      //更新界面
      _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
      _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
      _preview.frame = CGRectMake(0, 0, CGRectGetWidth(self.centerView.frame), CGRectGetHeight(self.centerView.frame));
      [self.centerView.layer insertSublayer:self.preview atIndex:0];
      [_session startRunning];
    });
  });
}

在viewWillAppear和viewWillDisappear里对session做优化(timer是个扫描动画的计时器)

 - (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  if (_session && ![_session isRunning]) {
    [_session startRunning];
  }
  timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(scanningAnimation) userInfo:nil repeats:YES];
  [self setupCamera];
}

 - (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  _count = 0;
  [timer invalidate];
  [self stopReading];
}

处理扫描结果

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

  NSString *stringValue;
  if ([metadataObjects count] >0){
    AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
    stringValue = metadataObject.stringValue;
    NSLog(@"%@",stringValue);
  }
  [_session stopRunning];
  [timer invalidate];
  _count ++ ;
  [self stopReading];
  if (stringValue && _count == 1) {
    //扫描完成
  }
}

用二维码扫描器扫描自己的二维码:

NSString *url = [NSURL URLWithString:@"html/judgement.html" relativeToURL:[ZXApiClient sharedClient].baseURL].absoluteString;

  if ([stringValue hasPrefix:url]) {
    //如果扫出来的url是自己的域名开头的,那么做如下的处理
  }

最后附上自己完整的源码:

// Created by Ydw on 16/3/15. 
// Copyright © 2016年 IZHUO.NET. All rights reserved. 
//

import “ViewController.h” 
import <AVFoundation/AVFoundation.h>

@interface ViewController () 
{ 
int number; 
NSTimer *timer; 
NSInteger _count; 
BOOL upOrdown; 
AVCaptureDevice *lightDevice; 
}

@property (nonatomic,strong) UIView *centerView;//扫描的显示视图

/** 
* 二维码扫描参数 
*/ 
@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 (nonatomic,retain) UIImageView *imageView;//扫描线

(void)setupCamera;
(void)stopReading;
@end 

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  if (_session && ![_session isRunning]) {
    [_session startRunning];
  }
  timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(scanningAnimation) userInfo:nil repeats:YES];
  [self setupCamera];
}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.view.backgroundColor = [UIColor clearColor];
  self.automaticallyAdjustsScrollViewInsets = NO;

  _count = 0 ;
  //初始化闪光灯设备
  lightDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  //扫描范围
  _centerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
  _centerView.backgroundColor = [UIColor clearColor];
  [self.view addSubview:_centerView];

  //扫描的视图加载
  UIView *scanningViewOne = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
  scanningViewOne.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4];
  [self.centerView addSubview:scanningViewOne];

  UIView *scanningViewTwo = [[UIView alloc]initWithFrame:CGRectMake(0, 120, (self.view.frame.size.width-300)/2, 300)];
  scanningViewTwo.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4];
  [self.centerView addSubview:scanningViewTwo];

  UIView *scanningViewThree = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)/2+150, 120, (self.view.frame.size.width-300)/2, 300)];
  scanningViewThree.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4];
  [self.centerView addSubview:scanningViewThree];

  UIView *scanningViewFour = [[UIView alloc]initWithFrame:CGRectMake(0, 420, self.view.frame.size.width,CGRectGetHeight(self.view.frame)- 420)];
  scanningViewFour.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4];
  [self.centerView addSubview:scanningViewFour];


  UILabel *labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(15, 430, self.view.frame.size.width - 30, 30)];
  labIntroudction.backgroundColor = [UIColor clearColor];
  labIntroudction.textAlignment = NSTextAlignmentCenter;
  labIntroudction.textColor = [UIColor whiteColor];
  labIntroudction.text = @"请将企业邀请码放入扫描框内";
  [self.centerView addSubview:labIntroudction];

  UIButton *openLight = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)/2-25, 470, 50, 50)];
  [openLight setImage:[UIImage imageNamed:@"灯泡"] forState:UIControlStateNormal];
  [openLight setImage:[UIImage imageNamed:@"灯泡2"] forState:UIControlStateSelected];
  [openLight addTarget:self action:@selector(openLightWay:) forControlEvents:UIControlEventTouchUpInside];
  [self.centerView addSubview:openLight];

  //扫描线
  _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)/2-110, 130, 220, 5)];
  _imageView.image = [UIImage imageNamed:@"scanning@3x"];
  [self.centerView addSubview:_imageView];
}

- (void)viewWillDisappear:(BOOL)animated {
  _count= 0;
  [timer invalidate];
  [self stopReading];
}

pragma mark -- 设置参数
- (void)setupCamera {

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];

    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    _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];
    }

    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes = [NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil];

    dispatch_async(dispatch_get_main_queue(), ^{
      //更新界面
      _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
      _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
      _preview.frame = CGRectMake(0, 0, CGRectGetWidth(self.centerView.frame), CGRectGetHeight(self.centerView.frame));
      [self.centerView.layer insertSublayer:self.preview atIndex:0];
      [_session startRunning];
    });
  });
}

//扫描动画
- (void)scanningAnimation {
  if (upOrdown == NO) {
    number ++;
    _imageView.frame = CGRectMake(CGRectGetWidth(self.view.frame)/2-115, 130+2*number, 230, 5);
    if (2*number == 280) {
      upOrdown = YES;
    }
  }
  else {
    number --;
    _imageView.frame = CGRectMake(CGRectGetWidth(self.view.frame)/2-115, 130+2*number, 230, 5);
    if (number == 0) {
      upOrdown = NO;
    }
  }
}

- (void)stopReading {
  [_session stopRunning];
  _session = nil;
  [_preview removeFromSuperlayer];
  [timer invalidate];
  timer = nil ;
}

-(void)openLightWay:(UIButton *)sender {

  if (![lightDevice hasTorch]) {//判断是否有闪光灯
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前设备没有闪光灯,不能提供手电筒功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
    return;
  }
  sender.selected = !sender.selected;
  if (sender.selected == YES) {
    [lightDevice lockForConfiguration:nil];
    [lightDevice setTorchMode:AVCaptureTorchModeOn];
    [lightDevice unlockForConfiguration];
  }
  else
  {
    [lightDevice lockForConfiguration:nil];
    [lightDevice setTorchMode: AVCaptureTorchModeOff];
    [lightDevice unlockForConfiguration];
  }
}

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

  NSString *stringValue;
  if ([metadataObjects count] >0){
    AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
    stringValue = metadataObject.stringValue;
    NSLog(@"%@",stringValue);
  }
  [_session stopRunning];
  [timer invalidate];
  _count ++ ;
  [self stopReading];
  if (stringValue && _count == 1) {
    //扫描完成
  }
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

@end

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


# ios  # 摇一摇功能实现  # ios摇一摇功能的实现  # ios扫一扫功能实现  # iOS通过UISwitch控制摇一摇  # iOS仿微信摇一摇功能  # IOS微信摇一摇声音无法播放的解决办法  # iOS仿微信摇一摇动画效果加震动音效实例  # IOS 实现摇一摇的操作  # iOS实现微信朋友圈与摇一摇功能  # iOS使用CoreMotion实现摇一摇功能  # 自己的  # 判断是否  # 器中  # 是个  # 很好  # 计时器  # 可以通过  # 请将  # 两步  # 一扫  # 大家多多  # 一响  # 并让  # 里对  # 检测方法  # 加载  # AVCaptureSessionPresetHigh  # scanningAnimation  # canAddInput  # setSessionPreset 


相关文章: Python多线程使用规范_线程安全解析【教程】  建站之星后台搭建步骤解析:模板选择与产品管理实操指南  如何通过商城免费建站系统源码自定义网站主题?  最好的网站制作公司,网购哪个网站口碑最好,推荐几个?谢谢?  合肥做个网站多少钱,合肥本地有没有比较靠谱的交友平台?  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?  猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?  如何在IIS管理器中快速创建并配置网站?  如何用美橙互联一键搭建多站合一网站?  Swift开发中switch语句值绑定模式  c# Task.ConfigureAwait(true) 在什么场景下是必须的  制作网站怎么制作,*游戏网站怎么搭建?  建站之星后台密码遗忘?如何快速找回?  详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)  如何快速启动建站代理加盟业务?  制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?  C++时间戳转换成日期时间的步骤和示例代码  开封网站制作公司,网络用语开封是什么意思?  ,如何利用word制作宣传手册?  洛阳网站制作公司有哪些,洛阳的招聘网站都有哪些?  Android自定义控件实现温度旋转按钮效果  网站建设设计制作营销公司南阳,如何策划设计和建设网站?  东莞市网站制作公司有哪些,东莞找工作用什么网站好?  c++ stringstream用法详解_c++字符串与数字转换利器  太原网站制作公司有哪些,网约车营运证查询官网?  网站制作的方法有哪些,如何将自己制作的网站发布到网上?  网站app免费制作软件,能免费看各大网站视频的手机app?  如何确认建站备案号应放置的具体位置?  建站之星安装路径如何正确选择及配置?  h5在线制作网站电脑版下载,h5网页制作软件?  深圳 网站制作,深圳招聘网站哪个比较好一点啊?  小米网站链接制作教程,请问miui新增网页链接调用服务有什么用啊?  如何在建站之星网店版论坛获取技术支持?  教学网站制作软件,学习*后期制作的网站有哪些?  子杰智能建站系统|零代码开发与AI生成SEO优化指南  如何在Golang中实现微服务服务拆分_Golang微服务拆分与接口管理方法  官网建站费用明细查询_企业建站套餐价格及收费标准指南  一键网站制作软件,义乌购一件代发流程?  深圳网站制作平台,深圳市做网站好的公司有哪些?  如何在Windows环境下新建FTP站点并设置权限?  网站视频怎么制作,哪个网站可以免费收看好莱坞经典大片?  c# 在高并发场景下,委托和接口调用的性能对比  北京建设网站制作公司,北京古代建筑博物馆预约官网?  javascript中的try catch异常捕获机制用法分析  ,南京靠谱的征婚网站?  如何安全更换建站之星模板并保留数据?  建站之星备案流程有哪些注意事项?  专业公司网站制作公司,用什么语言做企业网站比较好?  网站制作软件免费下载安装,有哪些免费下载的软件网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。