O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

21.4. Detecting Shakes on an iOS Device

Problem

You want to know when the user shakes an iOS device.

Solution

Use the motionEnded:withEvent: method of any object in your application that is of type UIResponder. This could be your view controller(s) or even your main window object.

Discussion

The motionEnded:withEvent: method of a responder object gets called whenever a motion has been captured by iOS. The simplest implementation of this method is this:

- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    /* Handle the motion */
}

The motion parameter, as you can see, is of type UIEventSubtype. One of the values of type UIEventSubtype is UIEventSubtypeMotionShake, which is what we are interested in. As soon as we detect this event, we know that the user has shaken her iOS device. Now go to the implementation of your view controller and handle the motionEnded:withEvent: method:

- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (motion == UIEventSubtypeMotionShake){
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:@"Shake"
                                   message:@"The device is shaken"
                                  delegate:nil
                         cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

If you now simulate a shake event even if you are on iOS Simulator (see this chapter’s Introduction), you will see that our window prints the text “Detected a shake” to the console window.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required