Nov 2009
Using the Shake API for iPhone OS 3
This cocoa touch tutorial will show you how receive notifications from the new “Shake API” included in the iPhone 3.0 OS. Figuring out where the notifications are even sent is confusing and isn’t document well in the SDK, but this tutorial will keep you up to speed. The method called when the iPhone / iPod touch shakes is similar to the touch API methods, but instead of views receiving the notification, the only object to receive the shake alert is the UIWindow. Trying to get the notification from a UIView simply won’t work.
To receive the notification, we’re going to have to subclass UIWindow. Start by creating a new NSObject class and call it “ShakeWindow”. Set the subclass of ShakeWindow to UIWindow. Now move the ShakeWindow.m file. Depending on what part of the shake you want your application to receive, add the method for such. Using notifications is probably the best message relaying pattern here because you have many objects that might want this information.
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
[[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self];
}
The other shake notifications are as such:
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event; - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
Most likely, you’ll want a controller object to receive the notification sent from the NSNotificationCenter object. Add this method to any class:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shake) name:@"shake" object:nil];
Finally, you’ll want open the MainWindow.xib nib file in Interface Builder and set the Window class to this new ShakeWindow class.






