26
27 static NSInteger shakeCount=0;
28 static NSDate *shakeStart;
29
30 NSDate *now=[[NSDate alloc] init];
31 // 摇晃 2秒内
32
NSDate *checkDate=[[NSDate alloc] initWithTimeInterval:2.0f
sinceDate:shakeStart];
33
34 //超过2秒 重计算晃动次数
35 if ([now compare:checkDate]==NSOrderedDescending||shakeStart==nil){
36 shakeCount=0;
37 [shakeStart release];
38 shakeStart=[[NSDate alloc] init];
39 }
40
41 [now release];
42 [checkDate release];
43
44 // 三轴摇晃的 G 力超过2则 列入计次
45 if (fabsf(acceleration.x)>2.0 || fabsf(acceleration.y)>2.0|| fabsf(acceleration.z)>2.0){
46 shakeCount++;
47
48 //2秒内侦测到4次则判定为 Shake 摇晃手机
49 if (shakeCount>4){
50 shakeCount=0;
51 [shakeStart release];
52 shakeStart=[[NSDate alloc] init];
53
54 //画面显示摇动文字
55 mylabel.text=@"地震了";
56
57 //设定2秒后自动还原
58
[NSTimer scheduledTimerWithTimeInterval:2.0f target:self
selector:@selector(cleartext) userInfo:nil repeats:NO];
59 }
60 }
61 }
62
63 -(void)cleartext{
64 mylabel.text=@"没现象";
65 }