LAA
LAA

Reputation: 21

Accelerometer - Shake not being detected - Cocoa Touch

Hello Im trying to get it so when the user shakes the device, the sound plays. However when I shake it, i get kicked out of the App

Here is the code which I have used

-(BOOL)canBecomeFirstResponder {
    return YES;
}


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

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

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"whip" ofType:@"wav"];
        if (theAudio) [theAudio release];
        NSError *error = nil;
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
        if (error)
            NSLog(@"%@",[error localizedDescription]);
        theAudio.delegate = self;
        [theAudio play];    

    }

}

Upvotes: 1

Views: 356

Answers (1)

Christian
Christian

Reputation: 1714

The app is not crashing due to the shake events. I just created a small test project with this code:

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

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

    [self becomeFirstResponder];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(motion == UIEventSubtypeMotionShake)
    {
        NSLog(@"Shake is working");
    }
}

This behaves correctly. I'd suggest commenting out the shake code and replacing it with a simple NSLog to make sure that the shake is working correctly, then working you way up from there, testing one piece at a time.

Also, in your viewDidDisappear code, I'd reverse the order of those two lines of code. (Almost) always, do the [super ..] calls first.

Upvotes: 3

Related Questions