IOS development detection device shake
Two Methods for device shaking detection are described below:
Method 1
First, add
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions
{
// Override point for customization after application launch
// Add detection shaking
Application. applicationSupportsShakeToEdit = YES;
}
Add
// Detect mobile phone shake
-(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: @ "prompt" message: @ "Congratulations! You get a 100-5 discount coupon" delegate: self cancelButtonTitle: @ "close" otherButtonTitles: nil
[AlertView show];
NSLog (@ "shaking detected ");
}
}
-(Void) prarGotProblem :( NSString *) problemTitle withDetails :( NSString *) problemDetails
{
[Self alert: problemTitle withDetails: problemDetails];
}
Method 2 Use CoreMotion
Introduce the required header file
# Import
The viewDidLoad to be detected initializes CMMotionManager and starts an NSTimer to detect changes in the X, Y, and Z axes.
-(Void) viewDidLoad {
[SuperviewDidLoad];
// Do any additional setup after loading the view.
NSTimer * AutoTimer = [NSTimerscheduledTimerWithTimeInterval: 1.0/60.0 target: selfselector: @ selector (autoChange) userInfo: nilrepeats: YES];
_ Manager = [[CMMotionManageralloc] init];
_ Manager. accelerometerUpdateInterval = 1.0/60.0;
[_ ManagerstartAccelerometerUpdates];
}
-(Void) autoChange
{
// Adjust x y z as needed
If (fabsf (_ manager. accelerometerData. acceleration. x)> 1.0 | fabsf (_ manager. accelerometerData. acceleration. y)> 1.2 | fabsf (_ manager. accelerometerData. acceleration. z)> 0.5)
{
NSLog (@ "I am shaking ..... ");
}
}
Note: method 1 is called only when the shaking is large, and method 2 can be adjusted as needed.