NSUserDefault for a simple game - ios

I'm creating a simple game app.
When the user click on the first button and the int click is 0, the he can click on the second button, and so on.
If the user firstly click on the second button and then on the first, his lifes will decreasing.
I'm having problems when the user reaches 0 lifes and the View returns on the first page.
Then when I click on the button to play again, I have 0 lifes and don't 3!
Here is my code:
#implementation livello1
int click=0;
int lifes=3;
-(void)updateLifes:(int)lifes{
if (lifes==1){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"1" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==2){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"2" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==3){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==0){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifes=3;
[self showLifes];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
gioca *giocaview = [[gioca alloc] initWithNibName:nil bundle:nil];
giocaview.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:giocaview animated:YES completion:nil];
}
}
-(void)showLifes{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"1"]) {
lifes=1;}
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"2"]) {
lifes=2;}
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"3"]) {
lifes=3;}
lifesLabel.text = [NSString stringWithFormat:#"%i",lifes];
}
- (IBAction)press1:(UIButton *)button1{
if ((button1.selected=YES && click==0)){
click=1;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes:(lifes)];
}
}
- (IBAction)press2:(UIButton *)button2{
if ((button2.selected =YES) && click==1){
click=2;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes:(lifes)];
}
}
- (void)viewDidLoad{
[super viewDidload];
[self showLifes];
}

Create another button for "Play Again" and link it to -(IBAction)buttonPressed:(UIButton *)playAgain and in that function reset the value of life to 3. And you don't need to pass lifes as it is a global variable (though that is not a very good practice). Though I am not really sure about your logic/ implementation for the click, you can use the following (slightly optimised) code :
#implementation livello1
int click=0;
int lifes=3;
-(void)updateLifes{
if (lifes!=0) {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setInteger:lifes forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifes=3;
[self showLifes];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
gioca *giocaview = [[gioca alloc] initWithNibName:nil bundle:nil];
giocaview.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:giocaview animated:YES completion:nil];
}
}
-(void)showLifes{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifesLabel.text = [NSString stringWithFormat:#"%i",[standardDefaults integerForKey:#"Userlifes"]];
}
- (IBAction)press1:(UIButton *)button1{
if ((button1.selected=YES && click==0)){
click=1;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes];
}
}
- (IBAction)press2:(UIButton *)button2{
if ((button2.selected =YES) && click==1){
click=2;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes];
}
}
- (IBAction)buttonPressed:(UIButton *)playAgain{ //the new function
lifes = 3;
click = 0;
[self updateLifes];
}
- (void)viewDidLoad{
[super viewDidload];
[self showLifes];
}

on playAgain Button click, setLife counter to 3.

Related

Switch state saved if sms sent

I have been trying to connect a switch to an SMS text which worked out fine, i was even able to save the state the switch was left in.
However now i need to save the state only if the SMS is sent, and if the user doesn't send the message but a switch is already turned on it should then alert them with a AlertView.
So far i have been able to save the state the switch was left it and connect a label to signify if it is "ON" or "OFF" in the SMS.
- (void)viewDidLoad {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
self->switch1.on = ([[standardDefaults stringForKey:#"switchKey"]
isEqualToString:#"On"]) ? (YES) : (NO);
if(switch1.on){
label.text = #"ON";
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:label.text forKey:#"labelkey"];
[defults synchronize];
} else label.text = #"OFF"; {
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:label.text forKey:#"labelkey"];
[defults synchronize];
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"labelkey"];
}
- (IBAction)switchChanged:(UISwitch *)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (sender.on == 0) {
label.text = #"OFF";
[standardDefaults setObject:#"Off" forKey:#"switchKey"];
} else if (sender.on == 1) {
label.text = #"ON";
[standardDefaults setObject:#"On" forKey:#"switchKey"];
}
[standardDefaults synchronize];
}
This is how i send the SMS.
- (IBAction)sendRequest:(id)sender
{
MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
messageVC.body = [#[label.text] componentsJoinedByString:#""];
messageVC.recipients = #[_phoneNumber.text];
messageVC.messageComposeDelegate = self;
[self presentViewController:messageVC animated:NO completion:NULL];
}
By using MFMessageComposeViewControllerDelegate delegate, you can find Message is sent or cancelled by user.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result
{
switch (result) {
case MessageComposeResultCancelled:
//show alert here as per your requirement break;
case MessageComposeResultFailed:
{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to send SMS!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
break;
}
case MessageComposeResultSent:
break;
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Refer this link -> Send sms

How to launch a different viewController on the second launch

Here the code I have under the viewController.m
This code will run when a user selects a viewController
-(void)switchViews {
UIStoryboard *mainStory = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [mainStory instantiateViewControllerWithIdentifier:schoolName];
[self presentModalViewController:vc animated:YES];
NSUserDefaults *defaultViewController = [NSUserDefaults standardUserDefaults];
[defaultViewController setObject:nil forKey:#"save"];
[defaultViewController synchronize];
}
This code will run on the second time the app is launched
-(void)loadNewView {
UIStoryboard *mainStory = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
NSUserDefaults *newUserDefault = [NSUserDefaults standardUserDefaults];
NSString *newVC = [NSString stringWithFormat:#"save", schoolName];
UIViewController *newViewController = [mainStory instantiateViewControllerWithIdentifier:newVC];
[self presentModalViewController:newViewController animated:YES];
}
Keeping in mind that schoolNameis a string
How can I run [self loadNewView] under the viewDidLoad but running it on the second time the app is launched?
You should do something like
id value = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (value) {
UIViewController *vc = [mainStory instantiateViewControllerWithIdentifier:value];
[self presentModalViewController:vc animated:YES];
} else {
// first time logic
}
in your AppDelegate or wherever you have your navigation logic. You should not have that logic in viewDidLoad.
-(void)viewDidLoad {
[super viewDidLoad];
NSString *launchCount = #"LaunchCount";
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSInteger count;
if([userDefaults objectForKey:launchCount]) {
count = [userDefaults integerForKey:launchCount];
}
else {
count = 0;
}
count++; //increment the launch count
[userDefaults setObject:[NSNumber numberWithInt:count] forKey:launchCount];
[userDefaults synchronize];
if([userDefaults integerForKey:launchCount] >= 2) {
// Do your thang
}
}
on ViewDidLoad function do something like this
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"HasLaunchedFirst"])
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"HasLauncheFirst"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self switchViews];
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:No forKey:#"HasLauncheFirst"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self loadNewView];
}

iOS NSArray Class Method [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I'm having trouble in create a NSArray class Method with Text Fields strings to use in another views controllers classes.
Let me show you what i have done:
First,in settings view controller, i'm collecting information in 3 text fields and saving with NSUserdefaults:
- (void)viewDidLoad
{
// Get the stored data before the view loads
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *toEmail = [defaults objectForKey:#"toEmail"];
NSString *ccEmail = [defaults objectForKey:#"ccEmail"];
NSString *bccEmail = [defaults objectForKey:#"bccEmail"];
// Update the UI elements with the saved data
self.toEmailTextField.text = toEmail;
self.ccEmailTextField.text = ccEmail;
self.bccEmailTextField.text = bccEmail;
[super viewDidLoad];
[self sideBarButton];
[self dismissTextFields];
}
- (IBAction)toEmailAction:(id)sender {
NSString *toEmail = self.toEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:toEmail forKey:#"toEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
- (IBAction)ccEmailAction:(id)sender {
NSString *ccEmail = self.ccEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:ccEmail forKey:#"ccEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
- (IBAction)bccEmailAction:(id)sender {
NSString *bccEmail = self.bccEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:bccEmail forKey:#"bccEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
Second I have another view controller with email API where I need to use the strings save with NSUserdefault in the settings view controller.(marked as text 1, text 2, and text 3)
#pragma mark - Email
- (IBAction)showEmail:(id)sender {
// Email Subject
NSString *emailTitle = #"GliLog Email";
// Email Content
NSString *messageBody = #"GliLog Email Test!!!";
// To address
NSArray *toRecipent = [NSArray arrayWithObject:#"text 1"];
NSArray *ccRecipient = [NSArray arrayWithObject:#"text 2"];
NSArray *bccRecipient = [NSArray arrayWithObject:#"text 3"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipent];
[mc setCcRecipients:ccRecipient];
[mc setBccRecipients:bccRecipient];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
How can i "pass" the strings from settings view controller to another view.
Best regards
You already have the answer in your first view, when reading the NSUserDefaults and storing to the strings:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *toEmail = [defaults objectForKey:#"toEmail"];
NSString *ccEmail = [defaults objectForKey:#"ccEmail"];
NSString *bccEmail = [defaults objectForKey:#"bccEmail"];
Just apply the same thing in second view controller,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *toRecipent = [NSArray arrayWithObject:[defaults objectForKey:#"toEmail"]];
NSArray *ccRecipient = [NSArray arrayWithObject:[defaults objectForKey:#"ccEmail"]];
NSArray *bccRecipient = [NSArray arrayWithObject:[defaults objectForKey:#"bccEmail"]];
if you are storing the data in the NSUserDefaults, just get the value from it.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString * toEmail = [defaults objectForKey:#"toEmail"];
NSString * ccEmail = [defaults objectForKey:#"ccEmail"];
A nice and simple tutorial about NSUserDefaults

Attach image to email [duplicate]

This question already has an answer here:
Attaching an image to an email?
(1 answer)
Closed 8 years ago.
So i have created so far 2 text fields which, the text fields are connected to the mail composer and whatever the user writes in them is what comes up in the mail composer however i do not know how to do the same for the UIImageView, i want the user to choose a picture or take a picture and that be automatically added to the mail composer as well.
#interface xyzViewController ()
#end
#implementation xyzViewController
- (IBAction)savedata:(id)sender; {
NSString *savestring = _mytextview.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
NSString *savestring1 = _mytextview1.text;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:savestring1 forKey:#"savedstring1"];
[defaults synchronize];
}
- (IBAction)loaddata:(id)sender; {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[_mytextview setText:loadstring];
[label setText:loadstring];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *loadstring1 = [defaults objectForKey:#"savedstring1"];
[_mytextview1 setText:loadstring1];
}
- (IBAction)dismiss:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)dismiss1:(id)sender {
[sender resignFirstResponder];
}
- (IBAction)takePhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendButton:(id)sender {
MFMailComposeViewController *mailContoller = [[MFMailComposeViewController alloc]init];
[mailContoller setMailComposeDelegate:self];
NSString *email = #"avip606#gmail.com";
NSString *email1 = #"avi_sp#hotmail.co.uk";
NSArray *emailArray = [[NSArray alloc]initWithObjects:email, email1, nil];
NSString *message = [#[_mytextview.text, _mytextview1.text] componentsJoinedByString: #"\n"];
[mailContoller setMessageBody:message isHTML:NO];
NSData *data = UIImagePNGRepresentation(_image);
[mailContoller addAttachmentData:data
mimeType:#"image/png"
fileName:#"image.png"];
[mailContoller setToRecipients:emailArray];
[mailContoller setSubject:#"IT WORKS!"];
[self presentViewController:mailContoller animated:YES completion:nil];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self mytextview] resignFirstResponder];
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Of course you can attach an image to a message, if you're using the MFMailComposeViewController class.
You just need to figure out how to use it's API of "addAttachmentData: mimeType: fileName:".
This related question might provide the answer you're looking for.

ObjectiveC: How to stop a music player from another view in Xcode?

I would like to stop my music playing from another view by using delegates. I already have that setup and i know there is this option...
- (void)viewWillDisappear:(BOOL)animated{
[player stop]; ///(my players name here and command to stop the player)
}
However i do not want to use that function because i have the music playing throughout. I have already added code to ensure my player does not overlap. But when i do want to stop my music i want to do so in a different view. I have tried the '[player stop];' function when the delegate is called but it does not work.
Can anyone help?
Thanks in advanced...
EDIT
HERE IS THE CODE FOR MY OPTIONS PAGE.H FILE:
#protocol onHandlerDelegate <NSObject>
- (void)off:(BOOL)success;
- (void)on:(BOOL)success;
-(void)volumeValueChange:(UISlider *)sender;
#end
#import <UIKit/UIKit.h>
#interface OptionsPage : UIViewController{
IBOutlet UISlider *VolumeSlider;
NSTimer *VolumeTimer;
IBOutlet UISwitch *onoroffmusic;
}
-(IBAction) UIBarButtonItem:(id)sender;
-(IBAction) SwitchMusic:(id)sender;
-(IBAction)changevolume:(id)sender;
#property (nonatomic, retain) UISwitch *onoroffmusic;
#property (nonatomic, strong) id<onHandlerDelegate> delegatePpty1;
#end
HERE IS MY OPTIONS PAGE .M FILE:
#import "OptionsPage.h"
#import "ViewController.h"
#interface OptionsPage ()
#end
#implementation OptionsPage
#synthesize onoroffmusic;
#synthesize delegatePpty1;
- (IBAction)changevolume:(id)sender{
int volume = VolumeSlider.value;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:volume] forKey:#"volume"];
[defaults synchronize];
[[self delegatePpty1]volumeValueChange:(VolumeSlider)];
}
-(IBAction) SwitchMusic:(id)sender{
if (onoroffmusic.on) {
[[self delegatePpty1] on:YES];
printf("done");
onoroffmusic.on = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"off"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"on"];
[defaults synchronize];
}
else {
/// do nothing
[[self delegatePpty1] off:YES];
printf("off");
onoroffmusic.on = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"on"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"off"];
[defaults synchronize];
ViewController *home = [[ViewController alloc] initWithNibName:nil bundle:nil];
[home.player stop];
}
}
-(IBAction) UIBarButtonItem:(id)sender{
ViewController *Backbutton = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:Backbutton animated:YES completion:nil];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad{
VolumeSlider.value = 0.3;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs valueForKey:#"volume"];
if(object == nil){
VolumeSlider.value = 0.3;
}
else{
VolumeSlider.value = [[[NSUserDefaults standardUserDefaults] objectForKey:#"volume"] intValue];
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
BOOL restoredBoolValue2 = [[defaults2 objectForKey:#"off"] boolValue];
BOOL restoredBoolValue1 = [[defaults2 objectForKey:#"on"] boolValue];
if (restoredBoolValue2) {
////donothing
onoroffmusic.on = FALSE;
}
if (restoredBoolValue1) {
////donothing
onoroffmusic.on = TRUE;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Within the two files i declare a delegate and my switches. Now just to receive that delegate in my view controller:
MY VIEWCONNTROLLER .H FILE:
#import "OptionsPage.h"
#interface ViewController : UIViewController <onHandlerDelegate>{
AVAudioPlayer *player;
}
#property (nonatomic, retain) AVAudioPlayer *player;
#end
HERE IS MY .M FILE:
Firstly I
#synthesize player;
Then check if my delegates have been called by using:
-(void)volumeValueChange:(UISlider *)sender
{
if (sender.value > 0.3) {
player.volume = sender.value;
}
else{
player.volume = 0.3;
}
}
-(void)on:(BOOL)success{
NSLog(#"Delegate Method Called");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"mykey1"];
[self play];
[player play];
}
-(void)off:(BOOL)success{
NSLog(#"Delegate Method Called");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"mykey1"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"mykey"];
[player stop];
player = nil;
[defaults removeObjectForKey:#"music"];
}
I then load the bool value of my nsuserdefults by using this:
- (void)viewDidLoad
{
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"mykey"] == nil ) {
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"music"] == nil) {
[self play];
}
}
}
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
BOOL restoredBoolValue2 = [[defaults2 objectForKey:#"mykey"] boolValue];
if (restoredBoolValue2) {
////donothing
[player stop];
}
BOOL restoredBoolValue1 = [[defaults2 objectForKey:#"mykey1"] boolValue];
if (restoredBoolValue1){
[self play];
}
And i have my play void function
-(void)play{
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"music"] == nil) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/Music.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
player.numberOfLoops = -1;
[player play];
player.volume = 0.3;
player.currentTime = 0.0;
[[NSUserDefaults standardUserDefaults] setObject:#"-" forKey:#"music"];
}
else {
[player stop];
}
}
and lastly in my app delegate.m file i :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:#"music"];
}
Make player a property and stop it like this:
[anotherView.player stop];
First you need to change onHandlerDelegate from strong to weak because it is a delegate.
Secondly you need an instance of OptionsPage on the second view controller and you need to implement the delegate and do optionPage.delegate = self after it this will work.

Resources