How to respond to the IPhone Shake Gesture
The IPhone 3.0 SDK includes support for detecting when a user “Shakes” the IPhone, this is intended to be a usability feature allowing app developers to implement Refresh or Read All functions on shake, wow those crazy guys at Apple really do know how to innovate!
It’s pretty easy to implement all you need to do is register your view controller as the first responder and listen for the motion event.
-(void) viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; [self becomeFirstResponder]; }
Once your controller is the First Responder you can receive the motion event like so:
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake) { refresh; } }
This will work beautifully but you will however notice that any views you present over this one will not respond to all touch events, for instance the keyboard will not show when you touch a text field, this is because you need to resign the First Responder before you present the view like so:
- (IBAction)showMyCustomView { [self resignFirstResponder]; [self presentModalViewController:myCustomViewController animated:YES]; }
As you can see this is all pretty easy and the only gotcha is the First Responder stuff, which also is pretty trivial.
Enjoy and please people, Shake Responsibly!

The view controller will also need to implement the canBecomeFirstResponder method and return YES.
Chris
16 Feb 10 at 2:26 am