IOS shake to determine how many seconds it takes

Source: Internet
Author: User

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;

}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.