@interface ViewController : UIViewController<UIAccelerometerDelegate>
- (void)loadView
{
......
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
accelerometer.delegate = self;
accelerometer.updateInterval = 1.0/10.0;
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
static NSInteger shakeCount = 0 ;
static NSDate* shakeStart ;
NSDate* now = [[NSDate alloc] init];
NSDate* checkDate = [[NSDate alloc] initWithTimeInterval:1.0f // 1秒内
sinceDate:shakeStart];
if ([now compare:checkDate] == NSOrderedDescending || shakeStart == nil)
{
shakeCount = 0 ;
shakeStart = [[NSDate alloc] init];
}
if (fabs(acceleration.x) > 2.0||
fabs(acceleration.y) > 2.0||
fabs(acceleration.z) > 2.0)
{
shakeCount ++ ;
if (shakeCount > 2) // 2次
{
shakeCount = 0 ;
shakeStart = [[NSDate alloc] init];
UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
message:@"刚刚摇动了一下"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
上面的代码检查在1秒内检测到2次认定为摇动。
可以检查比1.5大的绝对值来检测细微摇动,检查比2.0大的值来检测强烈摇动。