Detect Shake Gesture on a Device

iOS devices have the ability to detect shake gestures. In this tutorial we will detect a shake, and as a result an alertView will be displayed.

Update: Oct 20, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use ShakeGestureDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag a label to the main View. Give the Label a text of "Shake me". The main View should look like this.

First we need our view controller to respond to a shake gesture. So our view controller must become FirstResponder. In ViewController.m add the following method.in the interface section declare the following properties.

- (BOOL)canBecomeFirstResponder 
{
return YES;
}

We need to detect when a user starts and ends a shake. add the motionEnded:withEvent method

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake)
{
[self showAlert];
}
}

When a gesture is detected (and ended) the showAlert method is called.

-(IBAction)showAlert 
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello World" message:@"This is my first app!" delegate:nil cancelButtonTitle:@"Awesome" otherButtonTitles:nil];

[alertView show];
}

This method simply displays an alert view. Build and Run and shake the device. The alertview should be displayed.

You can download the source code of the ShakeGestureDemo at the ioscreator repository on github.