NSUserDefaults loses stored values third time - iphone

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];
}

Related

Objective c. Login user using storyboard

I have an storyboard with three view controllers, the init view with a button Init, the login view controller and the list view controller. When I click in the button init in the first view controller, I would like to verify whether the user logged in in order to switch to the login view or to the list view. How could I implement this using segues (segue conditionals??)
You could do something like this
BOOL isLoggedIn = [[NSUserDefaults standardUserDefaults] boolForKey:#"isLoggedIn"];
NSString *headingStoryboardID = isLoggedIn ? #"YourAlreadyLoggedInVC_ID" : #"YourLoginVC_ID";
if([headingStoryboardID isEqualToString:#"YourAlreadyLoggedInVC_ID"]) {
AlreadyLoggedInClass *vc1 = (AlreadyLoggedInClass *)[self.storyboard instantiateViewControllerWithIdentifier:#"YourAlreadyLoggedInVC_ID"];
[self presentViewController:vc2 animated:YES completion:nil];
} else {
LoginViewController *vc2 = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"YourLoginVC_ID"];
[self presentViewController:vc2 animated:YES completion:nil];
}
OBS: Ugly and uncompiled code but hope the concept gets across.
EDIT DUE TO COMMENT
To perform a push segue you call
[self.navigationController pushViewController:vc1 animated:YES];
instead.
You can Store your login value in user default when user login like this
in LOginViewController
-(void) doLogin
{
NSString * str = #"Loged In";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:str forKey:#"login"];
[defaults synchronize];
}
And in first view controller check whether this NSdefault value is nil or not.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userLogIn = [defaults objectForKey:#"login"];
if (userLogIn.length !=0) {
//then user Loged in
}else
{
//then user not Loged in
}
This code is just example you can change it acording to your need.

NSUserDefaults Not Fully Working For Settings In App

I have a settings view in my app that will give the user the option of one of the Tabs showing either a feed of mp3s from a podcast or mov from a podcast. I set it up on the first time running the app to display an AlertView asking what they prefer. I do that with this in the applicationDidFinishLaunching:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (! [defaults boolForKey:#"notFirstRun"]) {
UIAlertView *firstrun = [[UIAlertView alloc] initWithTitle:#"Sermon Preference" message:#"Do you prefer audio only, or video sermons? (This setting can be changed at any time in the Settings Page.)" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Audio", #"Video", nil];
[firstrun show];
[firstrun release];
[defaults setBool:YES forKey:#"notFirstRun"];
}
Then I set this in the AppDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *nope = #"Audio";
[defaults setObject:nope forKey:#"videosermons"];
[defaults synchronize];
}
if (buttonIndex == 1) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *yup = #"Video";
[defaults setObject:yup forKey:#"videosermons"];
[defaults synchronize]; }
}
On the Root View (Which is the audio listing of sermons) of the Navigation Controller for sermons I set this in viewWillAppear:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *currently = [defaults objectForKey:#"videosermons"];
if ([currently isEqualToString:#"Video"]) {
self.videoView = [[[VideoPodcastTableView alloc] initWithNibName:#"VideoPodcastTableView" bundle:[NSBundle mainBundle]] autorelease];
[self.navigationController pushViewController:_videoView animated:NO]; }
if ([currently isEqualToString:#"Audio"]) {
}
I also set up a Settings Tab with a segmentControl to reflect what has been selected. This is the issue:
If I click on Video in the firstRun popup, and then go straight to the Sermons tab, it stays on Audio Sermons. I can then navigate to the Settings Tab and it will show Video selected. Now, without selecting anything, I can go once more to the Sermons tab, and it will now go to the Video Sermons. Why is it that it is not getting the message to change until after I go to the settings?
The problem is that you're already loading your root view before the UIAlertView clickedButtonAtIndex: selector is called. After you launch your UIAlertView in your AppDelegate, your application continues loading your root view in the background.
viewWillAppear will have already run by the time a UIAlertView option has been selected.
To solve this, I'd recommend having another root view as your initial view. If you're using storyboards, have one segue going to a view controller that launches your alert view, and another segue going to your tab page. On first launch, segue to the alert view page, and otherwise segue to the tab page. This way your NSUserDefaults #"videosermons" key can be set before the tab view is loaded.

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?

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?

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.