IOS開發檢測設備搖動
發表時(shí)間:2021-1-10
發布人(rén):融晨科技
浏覽次數:46
設備搖動檢測的(de)兩種方法簡單的(de)記錄下
方法一
首先在(zài)delegate中添加
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch
//添加檢測晃動
application.applicationSupportsShakeToEdit = YES;
}
其次在(zài)需要(yào / yāo)檢測的(de)ViewController中添加
//檢測手機晃動
-(BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake)
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"恭喜你獲得100-5優惠劵一張" delegate:self cancelButtonTitle:@"關閉" otherButtonTitles: nil];
[alertView show];
NSLog(@"檢測到(dào)晃動");
}
}
-(void)prarGotProblem:(NSString *)problemTitle withDetails:(NSString *)problemDetails
{
[self alert:problemTitle withDetails:problemDetails];
}
方法二使用CoreMotion
引入需要(yào / yāo)的(de)頭文件
#import <CoreMotion/CoreMotion.h>
下需要(yào / yāo)檢測的(de) viewDidLoad初始化CMMotionManager 同時(shí)啓動一個(gè)NSTimer檢測X、Y、Z軸的(de)變化
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSTimer *AutoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];
_manager = [[CMMotionManager alloc]init];
_manager.accelerometerUpdateInterval=1.0/60.0;
[_manager startAccelerometerUpdates];
}
-(void)autoChange
{
//根據自己需求調節x y z
if (fabsf(_manager.accelerometerData.acceleration.x) > 1.0 || fabsf(_manager.accelerometerData.acceleration.y) > 1.2 || fabsf(_manager.accelerometerData.acceleration.z) > 0.5)
{
NSLog(@"我晃動了(le/liǎo) 。。。。。");
}
}
注:方法一中晃動幅度大(dà)的(de)情況下才會調用,方法二中可以(yǐ)根據自己的(de)需要(yào / yāo)調節