iOS實(shí)現(xiàn)“搖一搖”與“掃一掃”功能示例代碼
“搖一搖”功能的實(shí)現(xiàn):
iPhone對(duì) “搖一搖”有很好的支持,總體說(shuō)來(lái)就兩步:
在視圖控制器中打開(kāi)接受“搖一搖”的開(kāi)關(guān);
- (void)viewDidLoad {
// 設(shè)置允許搖一搖功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
// 并讓自己成為第一響應(yīng)者
[self becomeFirstResponder];
}
在“搖一搖”觸發(fā)的制定的方法中實(shí)現(xiàn)需要實(shí)現(xiàn)的功能(”搖一搖“檢測(cè)方法)。
// 搖一搖開(kāi)始搖動(dòng)
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
NSLog(@"開(kāi)始搖動(dòng)");
//添加“搖一搖”動(dòng)畫(huà)
[self addAnimations];
//音效
AudioServicesPlaySystemSound (soundID);
return;
}
// “搖一搖”取消搖動(dòng)
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
NSLog(@"取消搖動(dòng)");
return;
}
// “搖一搖”搖動(dòng)結(jié)束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (event.subtype == UIEventSubtypeMotionShake) { // 判斷是否是搖動(dòng)結(jié)束
NSLog(@"搖動(dòng)結(jié)束");
}
return;
}
”搖一搖“的動(dòng)畫(huà)效果:
- (void)addAnimations {
//音效
AudioServicesPlaySystemSound (soundID);
//讓上面圖片的上下移動(dòng)
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;
//讓下面的圖片上下移動(dòng)
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"];
}
注意:在模擬器中運(yùn)行時(shí),可以通過(guò)「Hardware」-「Shake Gesture」來(lái)測(cè)試「搖一搖」功能。如下:

“掃一掃”功能的實(shí)現(xiàn):
基于AVCaptureDevice做的二維碼掃描器,基本步驟如下:
初始化相機(jī),生成掃描器
設(shè)置參數(shù)
- (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];
}
// 條碼類(lèi)型 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里對(duì)session做優(yōu)化(timer是個(gè)掃描動(dòng)畫(huà)的計(jì)時(shí)器)
- (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];
}
處理掃描結(jié)果
- (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]) {
//如果掃出來(lái)的url是自己的域名開(kāi)頭的,那么做如下的處理
}
最后附上自己完整的源碼:
// 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;//掃描的顯示視圖
/**
* 二維碼掃描參數(shù)
*/
@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 ;
//初始化閃光燈設(shè)備
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 = @"請(qǐng)將企業(yè)邀請(qǐng)碼放入掃描框內(nèi)";
[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 -- 設(shè)置參數(shù)
- (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];
}
// 條碼類(lèi)型 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];
});
});
}
//掃描動(dòng)畫(huà)
- (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:@"當(dāng)前設(shè)備沒(méi)有閃光燈,不能提供手電筒功能" 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
iOS開(kāi)發(fā)CGContextRef畫(huà)圖使用總結(jié)
這篇文章主要為大家詳細(xì)介紹了iOS開(kāi)發(fā)CGContextRef畫(huà)圖使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
談?wù)刬OS開(kāi)發(fā)之JSON格式數(shù)據(jù)的生成與解析
JSON格式取代了xml給網(wǎng)絡(luò)傳輸帶來(lái)了很大的便利,本篇文章主要介紹了iOS開(kāi)發(fā):對(duì)象直接轉(zhuǎn)化成JSON詳解,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01
iOS開(kāi)發(fā)系列--詳細(xì)介紹數(shù)據(jù)存取
本篇文章主要介紹了iOS開(kāi)發(fā)系列--詳細(xì)介紹數(shù)據(jù)存取,詳細(xì)介紹了IOS數(shù)據(jù)的存儲(chǔ)問(wèn)題,具有一定的參考價(jià)值,有興趣的同學(xué)可以了解一下。2016-11-11
cmake ios終端下執(zhí)行提示錯(cuò)誤 iOS version not found, tested: [5.0;5.1;6
這篇文章主要介紹了cmake ios終端下執(zhí)行提示錯(cuò)誤 iOS version not found, tested: [5.0;5.1;6.0;6.1;7.0;8.3]的解決方案的相關(guān)資料,需要的朋友可以參考下2016-10-10
一行iOS代碼實(shí)現(xiàn)圖片無(wú)限輪播器
一行iOS代碼實(shí)現(xiàn)圖片無(wú)限輪播器的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
右滑返回手勢(shì)和UIScrollView中手勢(shì)沖突的解決方法
這篇文章主要為大家詳細(xì)介紹了右滑返回手勢(shì)和UIScrollView中手勢(shì)沖突的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02
iOS開(kāi)發(fā)中使用Quartz2D繪圖及自定義UIImageView控件
這篇文章主要介紹了iOS開(kāi)發(fā)中使用Quartz2D繪圖及自定義UIImageView控件的方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11
iOS體驗(yàn)性優(yōu)化之RTL適配右滑返回的實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于iOS體驗(yàn)性優(yōu)化之RTL適配右滑返回實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
iOS中設(shè)置清除緩存功能的實(shí)現(xiàn)方法
清除緩存基本上都是在設(shè)置界面的某一個(gè)Cell,于是我們可以把清除緩存封裝在某一個(gè)自定義Cell中,現(xiàn)在位大家介紹一種最基礎(chǔ)的清除緩存的方法,感興趣的朋友一起看看吧2017-07-07
iOS中使用UIDatePicker制作時(shí)間選擇器的實(shí)例教程
這篇文章主要介紹了iOS中使用UIDatePicker制作時(shí)間選擇器的實(shí)例教程,實(shí)例中未選中的時(shí)間項(xiàng)目會(huì)講解一個(gè)將其變透明的方法,非常給力,需要的朋友可以參考下2016-05-05

