The following code detects the shaking time:
CMMotionManager * _ motionManager = [[CMMotionManager alloc] init];
NSOperationQueue * _ operationQueue = [[NSOperationQueue alloc] init];
BOOL _ isShake; // whether it is shaking
BOOL _ isOver = NO; // whether the shaking has ended
NSInteger _ beginTimestamp = 0; // the start time stamp of the lottery.
_ MotionManager. accelerometerUpdateInterval = 1;
-(Void) initShake {
[_ MotionManager startAccelerometerUpdatesToQueue: _ operationQueue withHandler: ^ (CMAccelerometerData * latestAcc, NSError * error ){
Dispatch_sync (dispatch_get_main_queue (), ^ (void ){
// Synchronize all operations
@ Synchronized (_ motionManager ){
_ IsShake = [self isShake: _ motionManager. accelerometerData];
If (_ beginTimestamp = 0 & _ isShake = YES ){
NSLog (@ "the lottery starts ");
_ BeginTimestamp = [[NSDate date] timeIntervalSince1970];
}
If (_ beginTimestamp! = 0 & _ isShake = NO ){
_ IsOver = YES;
}
// The Lottery ends.
If (_ isOver ){
// Stop shaking Detection
[_ MotionManager stopAccelerometerUpdates];
// Cancel other requests queued in the queue
[_ OperationQueue cancelAllOperations];
NSInteger currentTimestamp = [[NSDate date] timeIntervalSince1970];
// Duration of shaking
NSInteger second = currentTimestamp-_ beginTimestamp;
NSLog (@ "Shake end, duration: % d", second );
}
}
});
}];
}
-(BOOL) isShake :( CMAccelerometerData *) newestAccel {
BOOL isShake = NO;
// If the acceleration speed in any of the three directions is greater than 1.5, it is regarded as shaking. If the acceleration speed is less than 1.5, it is deemed that the lottery is over.
If (ABS (newestAccel. acceleration. x)> 1.5 | ABS (newestAccel. acceleration. y)> 1.5 | ABS (newestAccel. acceleration. z)> 1.5 ){
IsShake = YES;
}
Return isShake;
}