how to save login data using NSUserDefaults and checkbox in Xcode? - xcode

hi i am trying to store my username and password in my app with NSUserdefaults and checkbox.
my code is ..
In viewdidload
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:UserText.text forKey:#"infoString"];
[defaults setObject:PasswdText.text forKey:#"infoString1"];
[defaults synchronize];
UserText.text=[[NSUserDefaults standardUserDefaults] objectForKey:#"infoString"];
and
- (IBAction)checkButton:(id)sender {
if (!checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"checkbox_ticked.png"] forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.UserText.text=[defaults objectForKey:#"infoString"];
self.PasswdText.text = [defaults objectForKey:#"infoString1"];
checked = YES;
}
else if (checked) {
[checkBoxButton setImage:[UIImage imageNamed:#"checkbox_not_ticked.png"] forState:UIControlStateNormal];
checked = NO;
}
}
and my result is if i click checkbox means my textfield is refreshed.where i made mistake?
thanks in advance.

You should save the values in NSUserDefaults when User Performed Submit action, Like this
- (void)submitButtontapped {
if (checked) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:UserText.text forKey:#"infoString"];
[defaults setObject:PasswdText.text forKey:#"infoString1"];
[defaults synchronize];
UserText.text=[[NSUserDefaults standardUserDefaults] objectForKey:#"infoString"];
}
// do the next thing
}
- (IBAction)checkButton:(id)sender {
if (checked) {
checked = NO;
[checkBoxButton setImage:[UIImage imageNamed:#"checkbox_not_ticked.png"] forState:UIControlStateNormal];
} else {
checked = YES;
[checkBoxButton setImage:[UIImage imageNamed:#"checkbox_ticked.png"] forState:UIControlStateNormal];
}
}

Related

absoluteString "handleOpenURL " to match email attachment name?

I have a working code, but now find the need to import & save two different Sqlite files via email "Open in" option, I tried using UIAlertView to create to different save file paths but it only seems to work with one way
- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName]; [dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
}
Both file have specific file names so was wonder if I could use "if equal to string" & use an if statement after I have synchronised NSUserDefaults to give two file path save options
Thanks for any help in advance
This was my UIALertView try
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"What type of data do you want to import?"
message:#"Choose data type"
delegate:self
cancelButtonTitle:#"Import RM Name Data"
otherButtonTitles:#"Import Store Visit Data", nil];
NSInteger *buttonIndex = NULL;
NSLog(#"Button Index =%ld",(long)buttonIndex);
if (buttonIndex == 0)
{
}
else if (buttonIndex == 1)
{
databaseExportName = #"export.sql";
NSArray *pathssqlite3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathssqliteDir2 = [pathssqlite3 objectAtIndex:0];
filePathsqlite3 = [pathssqliteDir2 stringByAppendingPathComponent:databaseExportName];
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSMutableData *dbimport = [[NSMutableData alloc] initWithContentsOfURL:urlx];
NSError *writeError = nil;
[dbimport writeToFile:filePathsqlite3 atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
} } [alertdata show];
Still trying to resolve, was hoping this would work, but still cannot crack it
`- (void)handleOpenURL:(NSURL *)urlx {
NSData *dbimport = [[NSData alloc] initWithContentsOfURL:urlx];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dbimport forKey:#"import"];
[defaults synchronize];
NSLog(#"import saved");
if([[urlx absoluteString] isEqualToString:#"svrStoreData2.sql"])
{
NSLog(#"If statement called");
//
databaseName = #"svrStoreData2.sql";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathx = [documentsPath stringByAppendingPathComponent:databaseName];
[dbimport writeToFile:filePathx atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
//
else {
databaseExportName = #"export.sql";
NSString *documentsPathy = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *writeError = nil;
NSString *filePathy = [documentsPathy stringByAppendingPathComponent:databaseExportName];
[dbimport writeToFile:filePathy atomically:YES];
if (writeError)
{
NSLog(#"Error writing file: %#", writeError);
}
NSLog(#"If statement Not called");
}
}
}
`
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex(NSInteger)buttonIndex {
if ([alertView tag] == 14)
{
if (buttonIndex == 1)
{
[self reviewSave];
}
}
if ([alertView tag] == 11) {
if (buttonIndex == 1)
{
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];}
}
}
Solved the problem, I had another UIAlert, so by adding Tags sorted it

xcode NSUserDefaults not saving

1.Whatever I do the saveButton method won't save and it still returns 0 for REJECTIONS
2.Please help me fix my saveButton to userdefaults method
3.I've tried multiple things and the values still won't change
#import "CCViewController.h"
#interface CCViewController ()
#end
#implementation CCViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [NSUserDefaults integerForKey:#"REJECTIONS"];
self.rejectLabel.text=REJECTIONS;
self.acceptedLabel.text=ACCEPTED;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.customInputTextField resignFirstResponder];
}
- (IBAction)resetButton:(UIButton *)sender {
self.rejectLabel.text=#"0";
self.acceptedLabel.text=#"0";
}
- (IBAction)rejectButton:(UIButton *)sender {
int current=stringToInt(self.rejectLabel.text);
int test=stringToInt(self.customInputTextField.text);
if (test>0) {
self.rejectLabel.text=self.customInputTextField.text;
self.customInputTextField.text=nil;
} else {
current++;
self.rejectLabel.text=intToString(current);
}
if (stringToInt(self.rejectLabel.text)==3000) {
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Achievement Message" message:#"You have reached 3000 rejections!" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[alertView show];
}
}
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:#"%d", integer];
}
- (IBAction)acceptedButton:(UIButton *)sender {
int current=stringToInt(self.acceptedLabel.text);
int test=stringToInt(self.customInputTextField.text);
if (test>0) {
self.acceptedLabel.text=self.customInputTextField.text;
self.customInputTextField.text=nil;
} else {
current++;
self.acceptedLabel.text=intToString(current);
}
NSLog(#"after is: %i", current);
}
- (IBAction)unrejectButton:(UIButton *)sender {
int current=stringToInt(self.rejectLabel.text);
current--;
if (current>=0) {
self.rejectLabel.text=intToString(current);
} else {UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Error Message" message:#"You can not have negative rejections!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];}
NSLog(#"after is: %i", current);
}
- (IBAction)saveButton:(UIButton *)sender {
NSString *rejected=self.rejectLabel.text;
int reject=intToString(self.rejectLabel.text);
NSString *accepted=self.acceptedLabel.text;
NSUserDefaults *rejectTry=[NSUserDefaults standardUserDefaults];
[rejectTry setObject:self.rejectLabel.text forKey:REJECTIONS];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setValue:#"reject" forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setValue:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setObject:#"accepted" forKey:ACCEPTED];
}
NSLog(#"test save %# & %# & %# & %#", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text);
[rejectTry synchronize];
NSLog(#"test save %# & %# & %# & %#, &a %i", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text, picker_value);
}
- (IBAction)loadButton:(id)sender {
self.rejectLabel.text=REJECTIONS;
self.acceptedLabel.text=ACCEPTED;
}
#end
Still not saving to the keys rejections and accepted
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.acceptedLabel.text forKey:ACCEPTED];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"test save %# & %# & %# & %# pointers %# %#", REJECTIONS, ACCEPTED, self.rejectLabel.text, self.acceptedLabel.text, defaults, prefs);
It looks like you have muddled up your pointers. You have two references to the same instance of userDefaults yet you expect different results when writing to each one. Here, lets walk through your code
NSString *rejected=self.rejectLabel.text;
int reject=intToString(self.rejectLabel.text);
NSString *accepted=self.acceptedLabel.text;
NSUserDefaults *rejectTry=[NSUserDefaults standardUserDefaults];
Lets stop here. standardUserDefaults is a singleton object. You are not creating a user defaults object when you call this method. You then go on to set a value
[rejectTry setObject:self.rejectLabel.text forKey:REJECTIONS];
This works fine.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.rejectLabel.text forKey:REJECTIONS];
Now you have written over your previous value!
[[NSUserDefaults standardUserDefaults] setValue:#"reject" forKey:REJECTIONS];
And you do it again!
[[NSUserDefaults standardUserDefaults] setValue:self.rejectLabel.text forKey:REJECTIONS];
[[NSUserDefaults standardUserDefaults] setObject:#"accepted" forKey:ACCEPTED];
Conclusion
What you should be doing is creating a local variable like this NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; Then use this for all your writes. Then you will see how you are overwriting the value with key REJECTIONS multiple times

NSuserdefaults UISwitch

I have some problems on save the position of switch,any help?
- (IBAction)SWitchActionAño:(id)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (switchAño.on) {
[standardDefaults setBool:YES forKey:#"SwitchState"];
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MMM dd,yyyy HH:mm"];
diadelasemanalabel.text=[formatter stringFromDate:[NSDate date]];
} else {
[standardDefaults setBool:NO forKey:#"SwitchState"];
Año.text=#"";
}
}
but i have the problem here! I dont know what is the property!
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
//the error here:property switchAño not found on object....
if ([standardDefaults objectForKey:#"SwitchState"])
self.switchAño.on =[standardDefaults boolForKey:#"SwitchState"];
Try this in viewDidLoad
-(void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *standardDefaults = [[NSUserDefaults standardUserDefaults];
if ([standardDefaults boolForKey:#"SwitchState"] == YES) {
self.switchAño.on = YES;
}
else {
self.switchAño.on = NO
}

NSUserDefaults not loading the numbers I want it to

I'm trying to use NSUserDefaults to save two variables after app shutdown. One being firstBoot and the other showAgain. Prepare for bad code-
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults]; //Here is where it is supposed to be loading the firstBoot variable to check whether or not it is the first boot
NSInteger boot = [defaults1 integerForKey:#"firstBoot"];
firstBoot = boot; //Sort of pointless variable swapping
if (firstBoot == 0) //Detects if isn't first boot, checks whether or not showAgain is yes or no (1=yes, 0=no)
{
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSInteger boot = [defaults1 integerForKey:#"firstBoot"];
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
NSInteger show = [defaults2 integerForKey:#"showAgain"];
firstBoot = boot; //More var swapping
showAgain = show; //^^
}
else
{
firstBoot = 1; //If it is the first boot, or the variable wasn't 0, it sets them both to 1.
showAgain = 1;
}
if ((firstBoot == 1) || (showAgain == 1)) //Checks if its the firstBoot or showAgain is set to yes
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Check the 'About' tab for help!" //Displays alert
message:#""
delegate:self
cancelButtonTitle:#"Don't show again"
otherButtonTitles:#"OK", nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"firstboot and showagain != 1" //Displays alert if it isn't the first boot, or isn't 1 and showAgain isn't set to yes(1).
message:#""
delegate:self
cancelButtonTitle:#"wrong"
otherButtonTitles:#"OK", nil];
[alert show];
}
}
Alert-
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == [alertView cancelButtonIndex])
{
showAgain = 0; //If user clicks "Don't show again", set showAgain to off(0) and tell it it isn't the first boot anymore
firstBoot = 0;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setInteger:0 forKey:#"firstBoot"]; //Hopefully stores firstBoot as 0
[defaults1 synchronize];
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
[defaults2 setInteger:0 forKey:#"showAgain"]; //Again storing showAgain as 0
[defaults2 synchronize];
}
}
The first alert should pop up the very first time you run the app, while the second one is a debugger placeholder, and should run every time after the first time. For me, the second one is running first, telling me that firstBoot and showAgain != 1.
NSInteger boot = [defaults1 integerForKey:#"firstBoot"]; will return 0 until you have saved a value in your defaults. 0, NO or nil are returned for keys that don't have any values stored.
The correct way to handle this is to register default values before you try to retrieve these user defaults.
// register default values. until you save your own value "firstBoot" will return YES
// you should put these two lines in the `application:didFinishLaunchingWithOptions:`
// method of the AppDelegate. Add all userdefaults that should have default values there
NSDictionary *defaultUserDefaults = #{ #"firstBoot" : #YES };
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultUserDefaults];
// use BOOL instead of integer
BOOL firstBoot = [[NSUserDefaults standardUserDefaults] boolForKey:#"firstBoot"];
if (firstBoot) {
NSLog(#"first launch");
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"firstBoot"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else {
NSLog(#"has been launched before");
}
How would firstBoot be set to YES on the first boot? Who would have set it?
Call registerDefaults: at the start of the application for all properties that should have values different from 0 before they have been explicitely set. For example, with a key firstBoot = YES. Alternatively, use a property "notFirstBoot" where the return value for missing properties ("NO") is what you actually want.
And there is really no need to call standardUserDefaults again and again.

Xcode: Check if UIButton is hidden, using NSUserDefaults

How would I allow the app to save & load the current state of a button (i.e. if it is hidden, how would I save this, so that next time it will be hidden)? Also, I have it currently set so that when a button is pressed, all the other buttons become un-hidden. How can I set it so that certain ones don't become un-hidden if they have been set un-hidden in NSUserDefaults if you see what I mean?
Thanks
You can check with Apple's documentation on NSUserDefaults to get any additional information you need.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setObject:myBool boolForKey:#"hiddenButton"];
[defaults synchronize];
Then you can just pull it in the same way and set your hidden value.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
myButton.hidden = [defaults boolForKey:#"hiddenButton"];
EDIT:
This would be one way to implement, but it really depends on what you want.
myViewController.h
BOOL myButtonState;
myViewController.m
-(void)viewDidLoad {
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
myButton.hidden = [defaults boolForKey:#"hiddenButton"];
}
-(IBAction)buttonPressed {
myButtonState = TRUE;
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setObject:myButtonState boolForKey:#"hiddenButton"];
[defaults synchronize];
}

Resources