你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> IOS開發檢測設備搖動

IOS開發檢測設備搖動

編輯:關於IOS

設備搖動檢測的兩種方法簡單的記錄下

方法一

首先在delegate中添加

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

// Override point for customization after application launch

//添加檢測晃動

application.applicationSupportsShakeToEdit = YES;

}

其次在需要檢測的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(@"檢測到晃動");

}

}

-(void)prarGotProblem:(NSString *)problemTitle withDetails:(NSString *)problemDetails

{

[self alert:problemTitle withDetails:problemDetails];

}

方法二使用CoreMotion

引入需要的頭文件

#import

下需要檢測的 viewDidLoad初始化CMMotionManager 同時啟動一個NSTimer檢測X、Y、Z軸的變化

- (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(@"我晃動了 。。。。。");

}

}

注:方法一中晃動幅度大的情況下才會調用,方法二中可以根據自己的需要調節

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved