2

i have questions regarding the shake detection that posted here before, here is a reminder:

"Now ... I wanted to do something similar (in iPhone OS 3.0+), only in my case I wanted it app-wide so I could alert various parts of the app when a shake occurred. Here's what I ended up doing.

First, I subclassed UIWindow. This is easy peasy. Create a new class file with an interface such as MotionWindow : UIWindow (feel free to pick your own, natch). Add a method like so:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DeviceShaken" object:self];
    }
}

Now, if you use a MainWindow.xib (stock Xcode template stuff), go in there and change the class of your Window object from UIWindow to MotionWindow or whatever you called it. Save the xib. If you set up UIWindow programmatically, use your new Window class there instead.

Now your app is using the specialized UIWindow class. Wherever you want to be told about a shake, sign up for them notifications! Like this:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceShaken) name:@"DeviceShaken" object:nil];

To remove yourself as an observer:

[[NSNotificationCenter defaultCenter] removeObserver:self];

questions:

  1. where to put the notifications (i have a view based app) ?
  2. do i have to remove myself as an observe, what does it mean ?
  3. what is the if statement that i use to check if the shake accrued?
  4. how can i know if the shake event know it is "already in progress" ?

thanks.

Richard Stelling
  • 25,607
  • 27
  • 108
  • 188
omri
  • 305
  • 1
  • 3
  • 10
  • Duplicate http://stackoverflow.com/questions/150446/how-do-i-detect-when-someone-shakes-an-iphone – Lucas B Dec 07 '09 at 14:39

1 Answers1

6

In iPhone OS 3.x it is simple to receive motion events form any view that is set as the first responder.

In you view class override the method motionEnded:, like this:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(motion == UIEventSubtypeMotionShake && [self isViewLoaded])
    {
        //handle shake here...
    }
}

In addition, you will need to become the First Responder when the view is loaded and appears:

- (void)viewDidAppear:(BOOL)animated
{
    [self becomeFirstResponder];
    [super viewDidAppear:animated];

    //any extra set up code...
}

You may also have to respond to the canBecomeFirstResponder method.

- (BOOL)canBecomeFirstResponder 
{ 
    return YES; 
}

These can be used in any object that inherits form UIView.

Richard Stelling
  • 25,607
  • 27
  • 108
  • 188