Ohad Regev
Ohad Regev

Reputation: 5711

iOS: How to Implement a "Shake Device" event?

I want to a "Shake Device" event to my app - i.e., when the user shakes the device something happens. I tried implementing:

-(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake) {
        //something happens
    }
}

It doesn't seem to work.......
Does anyone knows which method I should use?

Upvotes: 1

Views: 7117

Answers (3)

abhi
abhi

Reputation: 620

Try using the below code, it worked fine for me.

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

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
                [super motionEnded:motion withEvent:event];
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

Upvotes: 5

zic10
zic10

Reputation: 2330

In addition to Taylor's solution, also make sure that your AppDelegate.m has this in it.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    application.applicationSupportsShakeToEdit = YES;
    return YES;
}

Upvotes: 0

Taylor Abernethy Newman
Taylor Abernethy Newman

Reputation: 1162

Might be to late to answer but in your viewDidLoad you need to include.

[self becomeFirstResponder];

Give that a try.

Upvotes: 1

Related Questions