How to save Application State using NSUserDefaults in iPhone? - 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.

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.

UILabel becomes null after facebook login (UILabel dosen't update)

I am working on adding facebook SSO and the SDK to my project. All of my main facebook code is in my AppDelegate.m and AppDelegate.h.
In my view controller [[[UIApplication sharedApplication] delegate] performSelector:#selector(callLogin)]; is called when I press a button.
The callLogin method in my AppDelegate.m looks like this:
- (void)callLogin{
facebook = [[Facebook alloc] initWithAppId:#"XXXXX" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:nil];
}
}
Then in my - (void)fbDidLogin method I call the method setInfo which is located in my viewcontroller.
//this method is located in AppDelegate.m
- (void)fbDidLogin {
NSLog(#"FACEBOOK DID LOGIN");
ViewController * vc = [[ViewController alloc]init];
[vc setInfo];
}
Finally, here is my -(void)setInfo code which is located in ViewController.m
-(void)setInfo{
infoL.text = [NSString stringWithFormat: #"Connected to Facebook!"];
NSLog(#"%#",infoL);
//NSLog returns null
}
From setInfo I am unable to change the label and NSLog returns that infoL is null. I can update the label through methods like ViewDidLoad, but not setInfo.
What am I doing wrong and how can I fix this?
The view controller won't get updated because you just created some random instance of the class that is not on your navigation stack. I suppose you could call
[ self.viewController setInfo ]
assuming that is the property name for the vc you pushed on the stack in applicationDidFinishLaunchingWithOptions although this wouldn't be considered great design. Id factor Facebook delegate stuff out out app delegate, create a Facebook controller singleton class that your view controller can feed off
I assume that infoL represents a UILabel. Do you create this label in code or is an outlet that is created automatically?
If you create infoL in code, where is it allocated/initted? Is it non-nil at any time before your setInfo method runs?

Saving UITextField Input

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.

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?