views:

290

answers:

1

hi, 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.

+4  A: 

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.

rjstelling
i don't have this methods in my ViewController, just add them?want it effect the viewDidLoad method?do i need to do something in the xib also ?
omri
Yes, just add them to the .m file
rjstelling
For some reason `- becomeFirstResponder` has no effect if called in the `- viewDidLoad` method.
rjstelling
You shouldn't need to add anything extra to the .nib
rjstelling
perfect! thank you :-)
omri
It works flawlessly. Thank you.
SEQOY Development Team