Saving UITextField Input - iphone

Ive had a look at many other questions regarding this (I know there are alot!), but none seem to satisfy my query.
Basically I have a view controller which includes two UITextFields.
The app is designed so that this page loads, the user inputs numbers, and then taps the background to get rid of the keyboard, and the values save. I then want this to be pre loaded in the text field every time the user navigates back to the page. I presume I will have to create another IBAction called saveData or something, but is there anyway to automatically save it when the background is tapped? Also to save the data I was thinking of using NSUserDefaults, are there any other methods to save data?
Any help is appreciated,
Michael
I use the following code for the editing and background tap part of my application:
-(IBAction) textFieldDoneEditing : (id) sender{
[sender resignFirstResponder];
}
-(IBAction) backgroundTap:(id) sender{
[self.textInputOne resignFirstResponder];
[self.textInputTwo resignFirstResponder];
}

NSUserDefaults will work nicely for this:
-(IBAction) backgroundTap:(id) sender {
NSString *inputOne = textInputOne.text;
NSString *inputTwo = textInputTwo.text;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:inputOne forKey:#"InputOne"];
[userDefaults setObject:inputTwo forKey:#"InputTwo"];
[textInputOne resignFirstResponder];
[textInputTwo resignFirstResponder];
[sender resignFirstResponder];
}
then in - (void)viewDidLoad call back the stored NSUserDefaults:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
textInputOne.text = [userDefaults objectForKey:#"InputOne"];
textInputTwo.text = [userDefaults objectForKey:#"InputTwo"];
Should work fine

If you want to save the data (especially if the app is closed) NSUserdefaults is a nice and easy way to do it. Other options include writing to your own plist file or setting up a core data store, but you're just saving two numbers so not sure you need all that.

Related

NSUserDefaults loses stored values third time

I used NsUserDefaults for login page.
First I enter username and password, push sub viewcontroller then I come again login page and automatically login and push subviewcontroller (I can login automatically 2 times) but third one page stay in login page because of the username and password value empty
oturumAcikMi is equal to session
When I write my code in viewDidLoad, I get error message like below so my code is in viewDidAppear
nested push animation can result in corrupted navigation bar
Unbalanced calls to begin/end appearance transitions for <...: 0xcda4250>.
Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
My code
- (void)viewDidAppear:(BOOL)animated {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSObject *session = [def objectForKey:#"sessionUsr"];
NSLog(#"%# ?????", session);
if(session != nil && ![session isEqual:#""])
{
[self ConnectToService];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
[def setObject:self.eposta.text forKey:#"sessionUsr"];
[def setObject:self.sifre.text forKey:#"sessionPass"];
[def synchronize];
}

Switching start up view controller Xcode

Say for example if I have two buttons one for apples and one for orange, and I select apples and takes me to the apples screen. How can I make it for now on every time I run the app it will go to the apples screen?
in viewDidLoad
if([[NSUserDefaults standardUserDefaults] objectForKey:#"fruit"] != nil)
{
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"fruit"]isEqualToString:#"apple"]) {
[self.navigationController pushViewController:appleVC animated:NO];
}
else{
[self.navigationController pushViewController:orangeVC animated:NO];
}
}
and on Button Methods
on Apple button
[[NSUserDefaults standardUserDefaults] setObject:#"apple" forKey:#"fruit"];
on Orange button
[[NSUserDefaults standardUserDefaults] setObject:#"orange" forKey:#"fruit"];
You can store information like this using NSUserDefaults.
You'd store a boolean bAppleSelected like this:
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setBool:bAppleSelected forKey=#"appleSelected"];
You can read it by accessing the default userDefaults:
BOOL bApple = [standardUserDefaults boolForKey=#"appleSelected"];
On your app delegate you must have some method that instantiates the very first controller and displays it in a window. You can just create an "apples controller" and push it there
You can use NSUserdefaults here,
NSString* fruit=#"apple";
[[NSUserDefaults standardUserDefaults]setObject:fruit forKey:#"controllerName"];
[[NSUserDefaults standardUserDefaults]synchronize];
and insted of the name string of your firstview controller in appdelegate file use the above NSUserDefaults.

IF statment not checking condition on first run

I'm new to programming and I have an app that has a login view on start up and request the user to enter their name which is used throughout out the program. Once they enter their name and log in they are presented with the main menu view. Their name is saved using NSUserdefaults.
The idea is that they will only have to login once (or again if they logout) so they should only see the login view the first time they run the app however once the app is started again it still shows the login screen and also you have to press the login button twice before you are taken to the main menu.
I know that the app is storing the details because it is used thought the app but I cant work out why. Here is my code. If someone could help it would be greatly appreciated.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if(tempStr.length==0)
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
LogInView *Logview = [[LogInView alloc] initWithNibName:#"LogInView" bundle:nil];
[self presentModalViewController:Logview animated:YES];
}
else
{
MainMenuView *mainview = [[MainMenuView alloc] initWithNibName:#"MainMenuView" bundle:nil];
[self presentModalViewController:mainview animated:YES];
}
}
Judging by your description what you want is
On viewDidLoad check to see if the user is logged in
If YES show the MainMenu
If NO show the LogInView
The code may look like this
- (void)viewDidLoad
{
[super viewDidLoad];
[self showCorrectController];
}
The show correct controller method could look like this
- (void)showCorrectController
{
UIViewController *viewController = nil;
if ([self isLoggedIn]) {
viewController = [[MainMenuView alloc] init];
} else {
viewController = [[LogInView alloc] init];
}
[self presentModalViewController:viewController animated:YES];
[viewController release]; viewController = nil;
}
A convenience method is called isLoggedIn which looks like this
- (BOOL)isLoggedIn
{
// The double negation just means we get a boolean response
return !![[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
}
Now edit your original method to something like this
-(IBAction)LogInButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
[self showCorrectController];
}
There are quite a few things that could be done to tidy this up a lot but this should be a start to get you going.
A word of caution on your naming of things. The convention is to start method and variable names with lowercased letters. Classes and constants start with uppercase letters.
It looks like the first time in:
The login screen shows up
The user presses login (and this method you're showing gets called)
The saved value isn't initially set, so this evaluates to true: if(tempStr.length==0)
You save the new value
You display another login screen
But I don't think you're showing all the code. What runs when the app launches?

UITextField save text

I've an UITextField for insert the name of the user.
And in the right of the navigation bar I have a button called "Next" for switch to the next view.
I've this method:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
[[NSUserDefaults standardDefaults] setObject:theTextField.text forKey:#"name_post"];
return YES;
}
As you can see I use NSUserDefaults for save my temporary text.
So, when I click the "return" key on the field's keyboard the text is saved.
The problem is when I click the next button at the top while the field's keyboard is still visible, because the above method is not called, and the text is not saved.
How can I fix my problem?
Write a method called "saveText" with the content of your textFieldShouldReturn: method, and call it both from the textFieldShouldReturn: method and the action of the button.
- (BOOL) NextButtonAction {
[textField resignFirstResponder];
[[NSUserDefaults standardDefaults] setObject:theTextField.text forKey:#"name_post"];
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
return [self NextButtonAction];
}
change the target of Next button to NextButtonAction, and call NextButtonAction from the delegate method textFieldShouldReturn and also make the textField member of your class so you can access it from both of the functions.
You can save the textfield text on the next button click .This way it will be independent where your keyboard is visible or not
- (void)viewDidDisappear:(BOOL)animated{
NSString *inputOne = textview.text;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:inputOne forKey:#"InputOne"];
}
This Worked for me incase the user did not exit the keyboard in the expected way
You can add an nstimer to the button that makes the button wait 1 second before going on.
Its a bad solution, but one second isn't much. the user will just think that the app is loading something HUGE. Just add a large image on the next page.

How to save Application State using NSUserDefaults in iPhone?

Following is what i am doing:
- (void) applicationWillTerminate: (UIApplication*) application {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:navigationController.viewControllers
forKey:#"diabetesstate"];
}
- (void) applicationDidFinishLaunching: (UIApplication*) application {
NSMutableArray *state = [[NSUserDefaults standardUserDefaults]
objectForKey:#"diabetesstate"];
if (state == nil) {
//Will initialize a new controller and put it as root view controller
}
else {
[navigationController setViewControllers:state animated:NO];
}
}
It looks like you're trying to add a UIViewController to the userdefaults? I doubt that will work.
I guess you'll have to put some identifer string or number in there that tells you which viewcontroller is currently displayed, and when the application starts basically check that value and set up your viewcontrollers accordingly.
I need to implement something similar for my application. I've got a list of objects, and when the user taps on one I am displaying a child object. My idea is to store the ID of the client object if one is currently being displayed, otherwise NULL. When the application starts I will check the value. If it's NULL I'll display the list of parent objects, otherwise I'll show the child object with the ID that's in userdefaults.