i am trying to save the state of UISwitch .If the UISwitch state is "ON" and when the user quits the app and starts it again ..the app should show the previous state and if the user plans to change the state of UISwitch to "OFF"..he should get a message saying previously he had "ON" state and change to state to "OFF"
if you guys help me out that would be great .Thanks
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
if(notifyMe.isOn == YES)
{
toggle = YES;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:notifyMe.on forKey:#"switchValueKey"];
[defaults synchronize];
NSLog(#"Notification is ON");
}
else
{
toggle = NO;
NSLog(#"Notification is OFF");
}
}
if ([cellDelegate respondsToSelector:#selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
Change your button action method like:
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:#"switchValueKey"];
if(notifyMe.isOn == YES)
{
toggle = YES;
NSLog(#"Notification is ON");
}
else
{
toggle = NO;
NSLog(#"Notification is OFF");
}
[defaults setBool:toggle forKey:#"switchValueKey"];
[defaults synchronize];
//You can show the message here
NSLog(#"Previous state was %d",previousState);
}
if ([cellDelegate respondsToSelector:#selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
When you want to get the stored data you can use:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:#"switchValueKey"];
Related
I have a settings view where i have provided the option for users to change their settings.
Settings view have a table view having 2 UISwitches. I need help with NSUserdefaults method for saving states, and how I can write the code to load my values.
Here is my code so far
In `cellForRowAtIndexPath` method:
[cell.switchButton addTarget:self action:#selector(switchButtonTapped:) forControlEvents:UIControlEventValueChanged];
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"myBool"];
BOOL hBool = [[ NSUserDefaults standardUserDefaults] boolForKey:#"myBool"];
NSLog(#"tag %i", tappedSwitch.tag);
if (cell.switchButton.tag == 0) {
[cell.switchButton setOn:hBool];
}
return cell;
}
- (void) switchButtonTapped: (id) sender {
tappedSwitch = (UISwitch *) sender;
switch (tappedSwitch.tag) {
case 0:
passcodeSwitchIsOn = tappedSwitch.isOn;
if (passcodeSwitchIsOn) {
GCPINViewController *PIN = [[GCPINViewController alloc]
initWithNibName:nil
bundle:nil
mode:GCPINViewControllerModeCreate];
PIN.messageText = #"Enter a passcode";
PIN.errorText = #"The passcodes do not match";
PIN.title = #"Set Passcode";
PIN.verifyBlock = ^(NSString *code) {
NSLog(#"setting code: %#", code);
code = saveString;
return YES;
};
[PIN presentFromViewController:self animated:YES];
[PIN release];
// method of saving
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:passcodeSwitchIsOn forKey:#"myBool"];
[defaults synchronize];
}
break;
case 1:
bluetoothSwitchIsOn = tappedSwitch.isOn;
if (bluetoothSwitchIsOn) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Bluetooth Switch" message:#"Bluetooth Switch is ON" delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
break;
default:
break;
}
[settingsTable reloadData];
}
Create a reference to your user defaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Set a value:
[defaults setBool:1 forKey:#"bluetooth"];
You can set this back to 0 when bluetooth is off:
[defaults setBool:0 forKey:#"bluetooth"];
The user default is identified by the string of your choice. In this case: #"bluetooth". The value for the default will be nil until you create it and set it to something else.
So you can say:
if (!bluetooth) // bluetooth is off
else // bluetooth is on
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
This can be used for handling your issue.
IBOutlet UISwitch * swi_yourswitch;
#property(nonatomic,retain) UISwitch * swi_yourswitch;
implimentation
#synthesise swi_yourswitch;
- (void) switchButtonTapped: (id) sender {
UISwitch * switchObj = (UISwitch*)sender;
if(switchObj == self.swi_yourswitch){
if (self.swi_yourswitch.on){
NSLog(#"On");
}
else{
NSLog(#"Off");
[self.swi_yourswitch setOn:0];
}
}
To store value
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"mybool"];
[[NSUserDefaults standardUserDefaults] synchronize];
To get stored value
[NSUserDefaults standardUserDefaults] valueForKey:#"mybool"]
I have a UITableView with a UISwitch button in it. I want that when I run my application default value of the UISwitch button should be ON. If I toggle the switch button from on to off the value in the plist should change to OFF. If I quit the app and then I again run my app the value should again default to ON in the plist.
I have tried using NSUserDefaults, it works i.e when I change the value from ON to OFF the value in NSUserDefaults also changes. But when the app is run again the default value is not set to ON.
- (void)viewDidLoad {
[super viewDidLoad];
settings = [[NSMutableArray alloc]initWithObjects:#"Clock",#"Time Format",#"Weather",#"Degrees",nil];
switchControl = [[UISwitch alloc]initWithFrame:CGRectMake(205, 110, 20, 15) ];
[self.switchControl addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:switchControl];
NSString *viewdid = #"ON";
userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:viewdid forKey:#"stateOfSwitch"];
}
- (void)viewWillAppear:(BOOL)animated {
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfSwitch"];
if([_value compare:#"ON"] == NSOrderedSame){
[switchControl setOn:YES animated:YES];
}
else {
[switchControl setOn:NO animated:YES];
}
[super viewWillAppear:animated];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 4;
}
-(void)switchChanged:(id)sender
{
app= (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
NSString *value = #"ON";
userdefaults = [NSUserDefaults standardUserDefaults];
if(!switchControl.on){
value = #"OFF";
[userdefaults setObject:value forKey:#"stateOfSwitch"];
}
[userdefaults setObject:value forKey:#"stateOfSwitch"];
[userdefaults synchronize];
}
//this is my second class where i am accessing my userdefaults key and depending on that hiding the views
- (void) viewWillAppear:(BOOL)animated
{
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfSwitch"];
if([_value compare:#"ON"] == NSOrderedSame){
newview.hidden = NO;
newnewview.hidden =NO;
firstview.hidden = NO;
secondview.hidden = NO;
thirdview.hidden = NO;
}
else if([_value compare:#"OFF"] == NSOrderedSame) {
newview.hidden = YES;
newnewview.hidden= YES;
firstview.hidden = YES;
secondview.hidden = YES;
thirdview.hidden = YES;
}
}
In appDelegate did finish loading write below statements
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
May be you have not dump new values to plist?
Try to call [[NSUserDefaults standardUserDefaults] synchronize]; after setting new value to NSUserDefaults.
Either do
// set when launching the app
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
or
// set when terminating
- (void)applicationWillTerminate:(UIApplication *)application
[[NSUserDefaults standardUserDefaults] setObject:#"OFF" forKey:#"stateOfSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Furthermore, you should test your NSString using isEqualToString: as compare: may lead to false positives (e.g. if one of the strings is nil).
You shouldn't store a string, which has the potential for parsing bugs, when NSUserDefaults is perfectly capable of storing BOOLs directly.
Just store it like this:
#define StateOfSwitch #"StateOfSwitch"
-(void)switchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:switchControl.on forKey:StateOfSwitch];
[[NSUserDefaults standardUserDefaults] synchronize];
}
and then later, load the value like this:
switchControl.on = [[NSUserDefaults standardUserDefaults] boolForKey:StateOfSwitch];
(Note it's a good idea to never use string keys directly, it's better to #define them to prevent typo errors. Plus you get command + click to jump to definition, autocompletion, etc.)
I want to store a float value into NSUserDefaults.
I also need to check that the float value exists..if not I need to assign some value in it.
and retrieve it...for the above I have the below code but it gives me an error.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:#"HANDWRITING_SIZE_SLIDER"] == YES) {
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[NSUserDefaults standardUserDefaults] floatForKey:#"HANDWRITING_SIZE_SLIDER"]];
}
Thanks for any help
Use the NSNumber class for this and store it via the setObject:forKey: method so you can check if it exists.
I'd also suggest the usage of constants as keys:
#define HANDWRITING_SIZE_SLIDER #"HSS"
Your code should be along these lines:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:HANDWRITING_SIZE_SLIDER] == nil) {
//doesn't exist in NSUserDefaults, set to default value...
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[defaults objectForKey:HANDWRITING_SIZE_SLIDER] floatValue];
}
Somewhere else in your app, you'd set the value in NSUserDefaults like this:
float sizeSliderValue = ...
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sizeSliderValue] forKey:HANDWRITING_SIZE_SLIDER];
Try this code:
-(IBAction)sliderAction:(id)sender
{
float sliderValue = [sender floatValue];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sliderValue] forKey:#"keySliderValue"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"keySliderValue"]);
}
Is there a method to store the state of a UISwitch with NSUserDefaults?
If the state is ON I'd like to set some action...
Can I do this?
Thanks!
The answer of hotpaw2 is good and can also work well for big segmented control (more than 2 states). But if you only want to store 2 states, why not just use [setBool:forKey:] like this
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:#"mySwitchValueKey"];
and get it out:
BOOL swichState = [userDefaults boolForKey:#"mySwitchValueKey"];
which imo, is much much simpler, no if else code at all, no string converting back and for
To save:
- (void)mySwitchAction:(id)sender
{
if (sender == mySwitch) {
BOOL mySwitchValue = [ sender isOn ];
NSString *tmpString = mySwitchValue ? #"1" : #"-1" ;
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
[ myNSUD setObject:tmpString forKey: #"mySwitchValueKey" ];
[ myNSUD synchronize ];
// do other stuff/actions
}
}
To initialize from saved state:
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
NSString *tmpString = [ myNSUD stringForKey: #"mySwitchValueKey"];
BOOL mySwitchValue = NO; // or DEFAULT_VALUE
if (tmpString != nil) {
mySwitchValue = ( [ tmpString intValue ] == 1 );
}
[mySwitch setOn: mySwitchValue];
Sorry for the constant questions, but in my app, you are able to toggle if 3 UILabels and 1 UIImageview's hidden property is YES or NO via UISwitchs on another page (The settings page). The weird part is, one of the UILabels is hidden, even when it is declared that it is not to be hidden. Here is my code on the settings page.
- (IBAction)changeswitch1 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (artworkswitch.on)
[prefs setInteger:1 forKey:#"AWKey"];
else
[prefs setInteger:0 forKey:#"AWKey"];
}
- (IBAction)changeswitch2 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (titleswitch.on)
[prefs setInteger:1 forKey:#"TKey"];
else
[prefs setInteger:0 forKey:#"TKey"];
}
- (IBAction)changeswitch3 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (artistswitch.on)
[prefs setInteger:1 forKey:#"AKey"];
else
[prefs setInteger:0 forKey:#"AKey"];
}
- (IBAction)changeswitch4 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (volumeswitch.on)
[prefs setInteger:1 forKey:#"VKey"];
else
[prefs setInteger:0 forKey:#"VKey"];
}
All of this is set as the 'value changed' action in IB for the 4 switches.
Here is the code for the main page
if ([prefs integerForKey:#"AWKey"] == 1)
currentArtwork.hidden = NO;
else if ([prefs integerForKey:#"AWKey"] == 0)
currentArtwork.hidden = YES;
if ([prefs integerForKey:#"TKey"] == 1)
currentSong.hidden = NO;
else if ([prefs integerForKey:#"TKey"] == 0)
currentSong.hidden = YES;
if ([prefs integerForKey:#"AKey"] == 1)
currentArtist.hidden = NO;
else if ([prefs integerForKey:#"AKey"] == 0)
currentArtist.hidden = YES;
if ([prefs integerForKey:#"VKey"] == 1)
volumeview.hidden = NO;
else if ([prefs integerForKey:#"VKey"] == 0)
volumeview.hidden = YES;
This is just a guess, since I don't know the res of the code. But maybe it is hidden because another UILabel is positioned infront of it?. You can try:
[self.view bringSubviewToFront:yourLabel];
-Oscar
My solution was to have the label/imageview's hidden property set to NO upon the first launch.