一、搖一搖功能的實作
iPhone 對搖動偵測有原生支援,整體只要兩步。
第一步,在視圖控制器中打開搖動開關,並把自己設為第一響應者:
- (void)viewDidLoad {
[super viewDidLoad];
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
[self becomeFirstResponder];
}
第二步,在三個 motion 回調中實作你要的行為,分別對應搖動開始、取消與結束:
- (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;
}
配套的上下移動動畫可以用 CABasicAnimation 對 position 做關鍵frame動畫:
- (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 建立,核心步驟是:建立輸入輸出、綁定代理、設定可識別的條碼型別、啟動 session,最後把預覽層貼到介面上。
- (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];
}
_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];
});
});
}
session 的開關建議放在 viewWillAppear 與 viewWillDisappear 中管理,避免頁面切換時浪費電量;同時用一個 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];
}
掃描結果透過 AVCaptureMetadataOutputObjectsDelegate 回傳,記得掃到後立刻停止 session 並取消 timer:
- (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]) {
// 是自己域名開頭的連結,做相應處理
}
以下是包含手電筒開關、掃描框遮罩與掃描線動畫的完整原始碼,可直接參考:
// 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;
@end
@implementation ViewController
- (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)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)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];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
return;
}
sender.selected = !sender.selected;
[lightDevice lockForConfiguration:nil];
[lightDevice setTorchMode:sender.selected ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[lightDevice unlockForConfiguration];
}
@end