Objective C: Shake problems

1.3k views Asked by At

I'm detecting a shake that will start the animation, and when it ends, it stops animating. Sometimes it works, but sometimes it doesn't realize the shake has ended so it'll never call the motionEnded method. Has anyone else had this problem? Solutions?

-(BOOL)canBecomeFirstResponder {
return YES;
}

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

-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:NO];
}

-(void)viewDidDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewDidDisappear:NO];
}

-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventSubtypeMotionShake )
{
    NSLog(@"1");
    [img startAnimating];
}
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventSubtypeMotionShake )
{
    NSLog(@"3");
    [img stopAnimating];
}
}
1

There are 1 answers

0
Tydeology On

Apple seems to discuss the "inconsistency" you're experiencing here: http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MotionEvents/MotionEvents.html

Under listing 4-2 it reads:

... However, there is one important difference between touch events and shaking-motion events. When the user starts shaking the device, the system sends a motion event to the first responder in a motionBegan:withEvent: message; if the first responder doesn’t handle the event, it travels up the responder chain. If the shaking lasts less than a second or so, the system sends a motionEnded:withEvent: message to the first responder. But if the shaking lasts longer or if the system determines the motion is not a shake, the first responder receives a motionCancelled:withEvent: message.

I would suggest adding a motionCancelled:withEvent callback to see if that's what's happening in those cases where you don't get a motionEnded call.