UISwitch move to OFF state when back button used - iphone

I have a main window where i use a setting button used with navigation controller. I have a view controller where i kept my UISwitch. My UISwitch works well with its functionality but when i go back the switch turns "OFF" automatically.
I tried using these,
[[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:#"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
but then the same problem exists. Since i have only one view controller i cant retrieve the NSUserDefaults.
Any Suggestions?

When you setup your view, either in the init method or in viewDidLoad do something like this.
[startTrackingButton setOn:[[NSUserDefaults standardUserDefaults] boolForKey:#"switchValue"]]
Then every time you switch is toggled save the state of the switch
[[NSUserDefaults standardUserDefaults] setBool:startTrackingButton.on forKey:#"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];

"Since i have only one view controller i cant retrieve the NSUserDefaults."
You can retrive the user defaults in the viewDIdLoad to read the switch position in that one view
So if you have only one viewController
save to NSSsuserDefaults as you are doing
In viewDidLoad read the switch state to retrive the position of the switch
save switch state in your switch action method
if (sender == _switch) {
BOOL mySwitchValue = [ sender isOn ];
NSString *tmpString = mySwitchValue ? #"1" : #"-1" ;
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
[ myNSUD setObject:tmpString forKey: #"mySwitchValueKey" ];
[ myNSUD synchronize ];
//save a key to read switch state in another view if required
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:self.barCodeSwitch.on forKey:#"switch1"];
[userDefaults synchronize];
}
}
Read the saved switch position in viewDidLoad
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
NSString *tmpString = [ myNSUD stringForKey: #"mySwitchValueKey"];
BOOL mySwitchValue = NO; // or DEFAULT_VALUE on/off
if (tmpString != nil) {
mySwitchValue = ( [ tmpString intValue ] == 1 );
}
[_autocompleteSwitch setOn: mySwitchValue];

Related

Why Isn't NSUserDefaults working with my UISwitch

I'm trying to setup a UISwitch that is off by default until the user turns it on. However it is showing ON by default now.
AppDelegate's didFinishLaunching:
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"pinCodeSwitch"];
if (!testValue) {
// since no default values have been set, create them here
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"pinCodeSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
VC's viewDidAppear:
UISwitch* testSwitch = [[[UISwitch alloc] init] autorelease];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"]) {
[testSwitch setOn:NO animated:NO];
}
self.pinCodeSwitch = testSwitch;
Method to save BOOL when UISwitch's value changed:
- (IBAction)pinCodeSwitchChanged:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"pinCodeSwitch"];
BOOL test = [[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"];
}
You're not getting to set the switch since you set 'pinCodeSwitch' to NO. It skips the if statement.
Change it to:
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"pinCodeSwitch"])
(Negate your test), then the switch will turn off.
you can specify this value in the Interface Builder by the "STATE" value to OFF.
and after that save the switch value by applying this code:
[YourUiSwitch setOn:NO animated:YES];
[[NSUserDefaults standardUserDefaults]setValue:YourUiSwitch forKey:#"youruiswitch"];
[[NSUserDefaults standardUserDefaults]synchronize];
and when the view did load comes load it from the defaults like this:`YourUiSwitch =
[[NSUserDefaults standardUserDefaults]valueForKey:#"youruiswitch"];`
GOOD LUCK BUDDY!

NSUserDefaults - storing and retrieving data

I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.
I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.
here's the code that Im displaying the NSUserDefaults stored info on a UILabel:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
if someone could point me in the right direction that would be great,
thanks
Put this text in
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
}
And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults
When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:
[[NSUserDefaults standardUserDefaults] synchronize];
This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.
Do not forget the use synchronize when you set some value
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:#"KEY_NAME"];
[defaults synchronize];
Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue = [defaults objectForKey:#"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : #"No Value";
Hope it helps
In Swift we can do it following way:
To save value:
let defaults = UserDefaults.standard
defaults.set(YOUR_VALUE, forKey: "YOUR_KEY_NAME")
To get value:
let defaults = UserDefaults.standard
let data = defaults.objectForKey("YOUR_KEY_NAME")
For more details visit:
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults

How To Connect NSUserDefaults To UISwitch?

So I have setup my settings bundle which works in the iPhone's settings app. I want to add one of the settings within my own app. I know I can use InAppSettings framework, but I just want to add one settings, not all of them, and I already have an page ready that I want to add this settings option to.
So I have replicated the cell with UISwitch in my app which looks the same as the settings one. My question is, how can I now connect this UISwitch to my NSUserDefaults so it functions as a settings UISwitch?
In my appDelegate, I have:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:#"No" forKey:#"isKgs"];
[defaults registerDefaults:appDefaults];
[defaults synchronize];
Edit - All related code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey: #"isKgs"];
[defaults synchronize];
}
The cell inside the app where I want the UISwitch to be
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
[switchView addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchView setOn:[[NSUserDefaults standardUserDefaults] boolForKey:#"isKgs"] animated:NO];
[switchView release];
}
And the settings bundle where I have the same UISwitch that can be acceded through iPhone settings app:
Edit 2:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (nil == [defaults objectForKey:#"isKgs"])
{
[defaults setBool:NO forKey: #"isKgs"];
}
else
{
}
[defaults synchronize];
It's easier to use a boolean variable if you want to use a UISwitch. In the app delegate, set the default value for the settings, if not existed:
// set the default settings
NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"testSwitch"];
if (!testValue) {
// since no default values have been set, create them here
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"testSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
And then create use the value from the NSUserDefaults settings to turn on the switch if needed:
UISwitch* testSwitch = [[[UISwitch alloc] init] autorelease];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"testSwitch"]) {
[testSwitch setOn:YES animated:NO];
}
You should head aporat's suggestion and use a BOOL instead. However, if you are insistent on using a string as in your question, then you will have to do this:
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"isKgs"] isEqualToString:#"No") {
[switch setOn:NO animated:NO];
}
However, if you use a BOOL, you can set the switch in one simple line:
[switch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:#"isKgs"] animated:NO];
This means that you must go back and set up the defaults like this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:NO forKey#"isKgs"];
[defaults synchronize];
At some point in your code you are going to have to check the switch state and write it back to userDefaults:
[[NSUserDefaults standardUserDefaults] setBool:[switch on] forKey:#"isKgsk"];
[defaults synchronize];
you can write the changes back to userDefaults in your switchChanged: function.
Also, if you always set your key to NO in didFinishLaunchingWithOptions: then it will never reflect changes made in the settings app, it will always be NO.... this is probably not what you want.

Saving and Retrieving UILabel value with NSUserDefaults

I trying to save UILabel value to NSUserDefaults. I did IBAction with this code:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:#"result"];
[prefs synchronize];
}
Then, I connect it to button with Touch Up Inside.
What log shows after I pressed the button:
result = 0;
When I pressed a second time, then it works.
result = "28.34";
What I'm doing wrong and how can I retrieve a result?
EDIT
With this code I display result in log. I put it to same action.
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
Your code looks correct, so the issue is probably not the function you posted but rather the code that contains your NSLog. You might be logging the value in a way that misses the first time it gets set.
Your log statement should be
NSLog(#"%#",[[NSUserDefaults
standardUserDefaults]
objectForKey:#"result"]);
This should be after you set the object in NSUserDefaults.
Add this to your applicationDidFinishLaunching in appDelegate or in init method in viewController(you have to create one) :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(prefs == nil)
{
[prefs setObject:#"anything" forKey:#"result"];
[prefs synchronize];
}

Can I change the apps view based on if a file has been saved?

Please help! I'm a newbie to programming and I'm having the following trouble. I am trying to write my first iphone app and I would like it to do the following.
When the app launches user enters name, presses button and goes to new view. Their name is saved to file and used through out the app. That much I have managed.
I would like the app to check to see if there is a saved file when it is launched and go directly to second view instead of the first view. I'm have search for days looking for an answer and I'm still not sure how to do this.
At the risk of seeming stupid do I use an IF statement and how do I write it. Please help.
Thanking you in advance.
You have to use NSUserDefaults for storing the user name and pass words. If you want to store more data's, have to use plist(Documents Directory) or core data or SQLite.
// Store the data
[[NSUserDefaults standardUserDefaults] setObject:#"yourPasswordString" forKey:#"YourKey"];
// Retrieve the data
NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:#"YourKey"];
Once you retrieved the data, you have to check the conditions like,
if(passWord == nil)
{
//load first view
}
else
{
// load second view
}
Thanks!
if you're using NSUserDefaults to save it then all you have to do is try reading the value into a string, then check if it is nil, if it is, then the files isn't there and you would load your first view, if it was, then load your second view.
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"yourKey"];
if(tempStr == nil)
{
//load your first view
}
else
{
// load your second view
}
You need to read your key back out in order to test if it is nil, the way you are doing this, you will never be nil and will always use the else choice, you need to set your object elsewhere, probably in the if statement.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if (tempStr == nil || [tempStr isEqualToString:""])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
ClubSearchViewController *CSearch = [[ClubSearchViewController alloc]initWithNibName:#"ClubSearchViewController" bundle:Nil];
[self presentModalViewController:CSearch animated:YES];
}
else
{
SearchMenu *SMenu = [[SearchMenu alloc]initWithNibName:#"SearchMenu" bundle:nil];
[self presentModalViewController:SMenu animated:YES];
}
}
-(IBAction)LogOutButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"" forKey:#"UserName"];
[prefs synchronize];
}