Search code examples
iphonecocoa-touchshakemotion-detection

Can't get shake events on iPhone


I am not being able to get shake events on iPhone.

I have followed other questions here with no result. I also tried following the GLPaint example from Apple, but it seems exactly like my source code, with a small diference. GLPaint's source code /works/, mine /doesn't/.

So, here it is what I have:

Controller.m

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeEnded) name:@"shake" object:nil];
}

ShakingEnabledWindow.m

- (void)shakeEnded {
    NSLog(@"Shaking ended.");
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake ) {
        // User was shaking the device. Post a notification named "shake".
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self];
        NSLog(@"Shaken!");
    }
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
}

My XIB has a window, which is a ShakingEnabledWindow and an object, my Controller.

I am running out of ideas here, hope someone can give me a hand. :)


Solution

  • I think you are incorrectly checking the motion type. You need to check against event.subtype instead of motion:

    -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if ( event.subtype == UIEventSubtypeMotionShake ) {
            // Put in code here to handle shake
        }
    }