設備搖動檢測的兩種方法簡單的記錄下
方法一
首先在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(@"我晃動了 。。。。。");
}
}