15

Apple annonced Shake API in iPhone SDK 3.0. I can not find any information regarding this new feature.

Who knows about how to use it? Any example, link will be good.

sashaeve
  • 9,387
  • 10
  • 48
  • 61

3 Answers3

36

The APIs you are looking for are in UIResponder:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;

Generally you just implement this:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  if (event.type == UIEventSubtypeMotionShake) {
    //Your code here
  }
}

in your UIViewController subclass (UIViewController is a subclass of UIResponder). Also, you want to handle it in motionEnded:withEvent:, not motionBegan:withEvent:. motionBegan:withEvent: is called when the phone suspects shaking is happening, but the OS can determine the difference between a user purposefully shaking, and incidental shaking (like walking up the stairs). If the OS decides it was not a real shake after motionBegan:withEvent: is called it will call motionCancelled: instead of motionEnded:withEvent:.

Louis Gerbarg
  • 43,356
  • 8
  • 80
  • 90
  • Am I right if I say that we need to add the code `[self becomeFirstResponder];` on the view we require shake gesture to work? – Parth Bhatt Sep 29 '11 at 05:36
  • 1
    You would be right in saying that. Also: (BOOL)canBecomeFirstResponder {return YES;} – akaru Jan 16 '12 at 18:02
7

I posted a complete 3.0 example in this thread:

How do I detect when someone shakes an iPhone?

Community
  • 1
  • 1
Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
  • Keep reading, my response to that post does use 3.0. I uses the events posted above, only I also explain the bit about needing to set the UIView to be first responder which is crucial to it actually working. – Kendall Helmstetter Gelner Jul 24 '09 at 17:40
3

Joe Hewitt recently committed some code to Three20 that utilizes the 3.0 shake event. Seems like you just need to implement some simple code within -motionBegan:withEvent: inside of your UIResponder.

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.type == UIEventSubtypeMotionShake) {
        ...
    }
}
Sebastian Celis
  • 12,185
  • 6
  • 36
  • 44