Search code examples
iphoneobjective-cxcodeipadmotion-detection

UIButton is dead after I change views and switch back


So I created a program where a sound occurs when the device is shaken. Theres a button, that when tapped stops the sound from being played at any time (This is the "reset" method). There's another button, that when pushed displays another view (This is the "infoView" method). The problem occurs when I go the "infoView" then go back to the first view. The sound still play when the device is shaken but the "reset" button becomes unresponsive. Here's what I have so far, any help would be appreciated.

PS. I'm wondering if it has anything to do with FirstResponders? I'm still trying to wrap my head around FirstResponders.

The .h

#import <UIKit/UIKit.h>
#import "AVfoundation/AVfoundation.h"

@interface OldTvViewController : UIViewController{
AVAudioPlayer *audioPlayer;
}
-(IBAction)reset;
-(IBAction)infoView:(id)sender;
@end

the .m

#import "OldTvViewController.h"
#import "AudioToolBox/AudioToolBox.h"
#import "infoViewController.h"

@implementation OldTvViewController

-(IBAction)infoView:(id)sender{
infoViewController *second = [[infoViewController alloc] initWithNibName:Nil bundle:Nil];
[self presentModalViewController:second animated:YES];
[second release];
}

-(BOOL) canBecomeFirstResponder{
return YES;
}

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

if (event.subtype == UIEventSubtypeMotionShake) {

    //Play throw sound
    if(audioPlayer.playing){
        [audioPlayer stop];
    } else{
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/bomb.mp3",[[NSBundle mainBundle] resourcePath]]];
        NSError *error;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        audioPlayer.numberOfLoops = 0; 
        [audioPlayer play];    
    }

}

}


-(IBAction)reset{
[audioPlayer stop];
}


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

- (void)viewDidLoad
{
[super viewDidLoad];
}

@end

Solution

  • when You go to info view then where your all button available in that class you try this code.

    -(void)viewWillDisapeers
     {
    
      [audioPlayer stop];
    
     }
    

    or add in this method

    -(IBAction)infoView:(id)sender
     {
     infoViewController *second = [[infoViewController alloc] initWithNibName:Nil bundle:Nil];
     [self presentModalViewController:second animated:YES];
     [audioPlayer stop];
     [second release];
     }