1

I'm trying to detect a shake in iOS6, seems every single example ever was written back in 2009 or so for iOS3, and nothing's working as it should. Here's my method:

- (void) motionEnded: (UIEventSubtype) motion withEvent: (UIEvent *) event {
    if (motion == UIEventSubtypeMotionShake) NSLog(@"Detected a shake");
}

I've tried what Apple suggest (making a canBecomeFirstResponder method that returns YES, and calling it), but it doesn't do anything. It's called fine, but has no impact on the shake not being recognized.

I've read some stuff about needing to create a custom version of my view, but I'd really rather not screw around with that because I didn't create the view programmatically and there are four or so of them.

Thanks in advance!

Kay
  • 12,918
  • 4
  • 55
  • 77
Luke
  • 9,512
  • 15
  • 82
  • 146
  • Please have a look: http://stackoverflow.com/questions/6042420/how-to-detect-shake-motion-in-iphone#6056424 – Shad Dec 04 '12 at 13:02

2 Answers2

16

Inside your viewController you have to override the method caneBecomeFirstResponder and answering yes, in viewDidAppear you have to set your viewController (self) to be the first responder. This is the code:

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) NSLog(@"Detected a shake");
}

-(BOOL)canBecomeFirstResponder {
    return YES;
}


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

    [self becomeFirstResponder];
}
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
Giuseppe Mosca
  • 1,323
  • 12
  • 18
  • I tried the code above on my devices: iPhone 4S, iPhone 5, iPad 3 and iPad 1 with IOS 5. The code above works fine on all devices. – Giuseppe Mosca Dec 04 '12 at 14:42
  • Then something else is causing a problem here, as the motionEnded method is never called. Just trying to track down exactly what. – Luke Dec 04 '12 at 14:44
  • 1
    Turns out I needed viewDidAppear, as opposed to viewDidLoad. No idea why. – Luke Dec 04 '12 at 14:50
-2

Turns out I needed viewDidAppear, as opposed to viewDidLoad. No idea why.

Luke
  • 9,512
  • 15
  • 82
  • 146
  • 2
    You shouldn't have made another post for the answer. SHould have accepted Giuseppe's post as the correct answer! – defactodeity Jul 05 '13 at 10:46
  • I feel that making the distinction between viewDidLoad (which I hadn't mentioned in the original question) and viewDidAppear warranted a separate answer. Giuseppe provided a solution, but I wanted to clarify the actual problem (which was using Load over Appear). – Luke Jul 06 '13 at 09:54
  • `viewDidLoad` just pertains to the view being loaded into memory. It doesn't have to do with the view being set up, ie: being in a state where it can become the first responder. – JaredH Mar 03 '15 at 18:16