UISwitch in ios - ios

In ViewDidLoad
{
NSLog(#"Switch Value %d",delegate.switchvalue);
if(delegate.switchvalue==1)
{
[onoffswitch setOn:YES];
}
else
{
[onoffswitch setOn:NO];
}
}
In Designing,
onoffswitch=[[UISwitch alloc]initWithFrame:(CGRectMake(200, 8, 50, 33))];
[onoffswitch addTarget:self action: #selector(flip:) forControlEvents:UIControlEventValueChanged];
// [onoffswitch setOn:YES];
In Switch Method,
-(IBAction)flip:(id)sender
{
if([sender isOn])
{
[onoffswitch setTag:1];
NSLog(#"%d",[sender tag]);
delegate.switchvalue=[sender tag];
NSLog(#"%d",delegate.switchvalue);
NSLog(#"ON");
NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:#selector(TimerTapped:) userInfo:nil repeats:YES];
[BirthTimer fire];
}
else
{
NSLog(#"OFF");
}
}
My Problem is,I set the switch mode in ON.If I go to another view,then change again off mode.
Any Idea Please Help me.
Thanks to advance for your help.
Using NSUserDefaults
-(IBAction)flip:(id)sender
{
[onoffswitch setTag:1];
delegate.switchvalue=[sender tag];
NSLog(#"%d",delegate.switchvalue);
if([sender isOn])
{
NSLog(#"ON");
isAlarm=1;
NSLog(#"%d",isAlarm);
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults]synchronize];
[switchdefault setInteger:delegate.switchvalue forKey:#"Switchcontrol"];
[switchdefault setBool:YES forKey:#"SwitchBool"];
[switchdefault synchronize];
NSTimer *BirthTimer=[NSTimer scheduledTimerWithTimeInterval:86400.0 target:self selector:#selector(TimerTapped:) userInfo:nil repeats:YES];
[BirthTimer fire];
}
else
{
NSLog(#"OFF");
isAlarm=0;
NSLog(#"%d",isAlarm);
}
}
In ViewWillappear
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
if([switchdefault boolForKey:#"SwitchBool"])
{
[onoffswitch setOn:YES animated:YES];
}
else
{
[onoffswitch setOn:YES animated:YES];
}
In ViewDidLoad of AnotherView
NSUserDefaults *switchdefault=[NSUserDefaults standardUserDefaults];
if ([switchdefault boolForKey:#"SwitchBool"])
{
delegate.switchvalue=1;
}
[switchdefault synchronize];

Use NSSUserDefault to store the status of your switch button and again while adding it to your view retrieve it from the same...
Store 1 once you switch it ON and the 0 for OFF mode.
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"values"];
and get it back like this,
NSInteger mode = [[NSUserDefaults standardUserDefaults] integerForKey:#"values"];
NOTE: I suggest you to add your switch button in the ViewWillAppear/ViewDidAppear.

If you want the switch to be set to delegate.switchValue every time your view appears, try moving this code from viewDidLoad to viewDidAppear:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if(delegate.switchvalue==1)
{
[onoffswitch setOn:YES];
}
else
{
[onoffswitch setOn:NO];
}
}

Related

How to retain Remove Ads in app purchase after app has closed

I have successfully removed ads from the app with an in app purchase.
The problem is that if I close the app and reopen. The ads start up again.
I have 2 main scenes. The GameOverScene and the GameScene. The In App Purchase happens in the GameOverScene.
GameOverScene.m :
- (void)OnRemoveADS {
[self showPurchaseAlert: IAP_Q_RemoveADS :0];
g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: #"REMOVEADS"];
// For HZInterstitialAd, HZVideoAd, and HZIncentivizedAd, just check the BOOL to see if an ad should be shown
if (!g_bRemoveADS) {
[HZInterstitialAd show];
[self removeBannerAds];
[self disableAds];
NSLog(#"Disable ads is called");
}
}
- (void)removeBannerAds {
HZBannerAdOptions *options = [[HZBannerAdOptions alloc] init];
[HZBannerAd placeBannerInView:self.view
position:HZBannerPositionBottom
options:options
success:^(HZBannerAd *banner) {
if (g_bRemoveADS) { // case (2)
// Just discard the banner
[banner setHidden: YES];
[banner removeFromSuperview];
banner = nil;
//_currentBannerAd = banner;
NSLog(#"Banner ad removed!GameOverScene");
} else {
// Keep a reference to the current banner ad, so we can remove it from screen later if we want to disable ads.
_currentBannerAd = banner;
}
NSLog(#"Ad Shown! GameOverScene");
}
failure:^(NSError *error) {
NSLog(#"Error = %#",error);
}];
}
- (void)disableAds {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"REMOVEADS"];
[_currentBannerAd removeFromSuperview]; // case (3)
}
GameScene.m :
-(id) init {
if (self = [super init]) {
if (!g_bRemoveADS) {
g_bRemoveADS=FALSE;
[[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:#"REMOVEADS"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
g_bRemoveADS=TRUE;
[[NSUserDefaults standardUserDefaults] setBool:g_bRemoveADS forKey:#"REMOVEADS"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
The way I'm trying to solve it is by using the same code from the GameOverScene.m in the AppDelegate.m that way when the app starts up it will remove the ads.
AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
g_bRemoveADS = [[NSUserDefaults standardUserDefaults] boolForKey: #"REMOVEADS"];
if (!g_bRemoveADS) {
[HZInterstitialAd show];
[self disableAds];
NSLog(#"Disable ads is called");
}
}
Out of my perspective you have one negation to much.
if (!g_bRemoveADS) { should be replaced with if (g_bRemoveADS) { in GameOverScene.m.
if (g_bRemoveADS) {
[HZInterstitialAd show];
[self removeBannerAds];
[self disableAds];
NSLog(#"Disable ads is called");
}
g_bRemoveADS evaluates to TRUE when the respective user-default is set. When it is set, then you call the removeBannerAds stuff etc. which seems to be the deactivation action.
You have to synchronise your NSUserDefaults after changing changing a value in your disableAds method with:
[[NSUserDefaults standardUserDefaults]synchronize];

iOS - Turn SFX off

I'm very new to iOS development. I've currently got an app with some SFX in there. I've found a couple of other threads which explain the approach / logic, which I full understand, but it's the code I'm after as I have no idea of the syntax.
If I were to use a UI Switch, how would I turn off any SFX that's used within the app?
Any help and assistance would be greatly appreciated.
Thank you all.
How are you using your sfx? If you could upload your code it would help. But you can try this?
- (IBAction)SwitchValueChanged:(id)sender
{
if([sender isOn])
{
NSLog(#"Switch is ON");
//On Your SFX
}
else
{
NSLog(#"Switch is OFF");
//Off Your SFX
}
}
I don't really understand what you mean by Some SFX So its hard to provide help
There might be an option for you. So in the
.h file where the switch to turn it off, put this code.
#interface SettingScreen : UIViewController<AVAudioPlayerDelegate,AVAudioSessionDelegate>
{
AVAudioPlayer *audioplayer;
}
in .m file
-(void)viewDidLoad
{
NSString* BS_path_blue=[[NSBundle mainBundle]pathForResource:#"Click" ofType:#"mp3"];
audioplayer =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:BS_path_blue] error:NULL];
audioplayer.delegate=self;
[audioplayer prepareToPlay];
UISwitch *soundsButton = [[UISwitch alloc]initWithFrame:CGRectMake(180, 8, 130, 27)];
[self.view addSubview:soundsOnOffButton];
[soundsOnOffButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
soundsButton.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"sound"];
}
-(void)buttonAction:(UIButton *)sender
{
if (soundsButton.on)
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"sound"];
[[NSUserDefaults standardUserDefaults] synchronize];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"sound"]==YES)
{
[audioplayer play];
}
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"sound"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
Now if you want to play a sound for something. (Button used as example) in another screen , add delegate and first four lines to your file then add this line to their action.
-(void)buttonAction:(UIButton *)sender
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"sound"]==YES)
{
[audioplayer play];
}
// other code
}
Hope it works.

How to Keep Sound Turned Off

I have a two buttons. One that shows when the sound is playing and one when the sound isn't playing. However, when I switch it off and switch view controllers. And i come back to the main menu view controller the sound is back on. I want to keep the sound on or off based on the user setting.
(IBAction)pauseSound
{
BOOL shouldPlaySound = YES;
[[NSUserDefaults standardUserDefaults] setBool:shouldPlaySound forKey:#"shouldPlaySound"];
if (![sound isPlaying]) {
[sound play];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOn.png"] forState:UIControlStateNormal];
}else {
[sound pause];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOff.png"] forState:UIControlStateNormal];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
A good way to do this is saving wether or not to play the Sound in the NSUserDefaults, so the setting is remembered by your app. Set it i.e. via
BOOL shouldMuteSound = ...//set it corresponding to your button presses/visibility
[[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:#"shouldMuteSound"];
//call this to immediatly update the userDefaults
[[NSUserDefaults standardUserDefaults] synchronize];
And load it via
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
I didn't get it at first that the buttons are inside the same viewController that plays the sound. That code should help you:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
if(!shouldMuteSound){
[self playSound];
}else{
[self stopSound];
}
}
- (void)playSound{
if(!sound){
NSString *path = [[NSBundle mainBundle] pathForResource:#"Main Menu" ofType:#"mp3"];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
sound.numberOfLoops = -1;
}
if (![sound isPlaying]){
[sound play];
}
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOn.png"] forState:UIControlStateNormal];
}
- (void)stopSound{
[sound pause];
[soundButton setBackgroundImage:[UIImage imageNamed:#"SoundOff.png"] forState:UIControlStateNormal];
}
- (IBAction)soundButtonTapped{
BOOL shouldMuteSound = [[NSUserDefaults standardUserDefaults] boolForKey:#"shouldMuteSound"];
shouldMuteSound = !shouldMuteSound;
[[NSUserDefaults standardUserDefaults] setBool:shouldMuteSound forKey:#"shouldMuteSound"];
[[NSUserDefaults standardUserDefaults] synchronize];
if(shouldMuteSound){
[self stopSound];
}else{
[self playSound];
}
}

save UIButton state iOS

I have a UIButton
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
checked = YES;
} else if (checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
checked = NO;
}
}
I want to save the user input, weather the button is checked or not, even after the app closes. Help me with codes anyone? I don't know the codes to use NSUserDefaults for saving BOOL state.
Use it by below way:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool: checked forKey:#"Status"];
[defaults synchronize];
To retrieve it,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL state = [defaults boolForKey:#"Status"];
Set images for both Normal and selected state of a button as
[checkBoxButton setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateSelected];
[checkBoxButton setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
and in IBAction set
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setSelected:NO];
checked = YES;
} else if (checked) {
[checkBoxButton setSelected:YES];
checked = NO;
}
}
Here is an Example:
if ([[NSUserDefaults standardUserDefaults] boolForKey:hasLaunchedOnceKey])
{
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:hasLaunchedOnceKey];
[[NSUserDefaults standardUserDefaults] synchronize]; //Saves the data
}
Where I have:
static NSString *hasLaunchedOnceKey = #"HasLaunchedOnce";
Declared before the #implementation statement.
See this for an extensive tutorial.
**Note: You do not need to declare anything in any sort of plist files afaik. You can simply check for and set these keys and they will be dynamically created if they don't exist. Works that way for me anyways.
Happy programming!
My way is too easy .. You don't need to take any other variable. On initialise set your button tag ZERO and after use this.
- (IBAction)checkButton : (id)sender {
if ([sender tag] == 0) {
[sender setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[sender setTag:1];
} else {
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
[sender setTag:0];
}
}
Thanks & Cheers .. May be helpfull..

NSUserDefault for a simple game

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.

Resources