NSUserDefaults Not Fully Working For Settings In App - iphone

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.

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.

What is the perfect way to make a logout from IOS app?

The below code is working but has a bug. The scenario is that, I begin by logging in to enter the app system. Once the login has succeeded, the app will set UserDefaults (UserId). After that, I can navigate the app views with stored UserId. Once I go to settings and tab logout, that will clean UserId and go to login view.
The BUG: When I login again to the app and click the home button to go to iPhone desktop and close the app, and return to open it again it still storing the UserId. So, if I go to the setting and log out that will clean UserId and will not go to login view. I don't know why.
The code:
- (IBAction)resetKeychain:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:#"Are you sure you want to logout?"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Logout"
otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showFromTabBar:self.tabBarController.tabBar];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex ==0) {
//logout
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
//delete user ID fro user Defaults
[defaults setObject:nil forKey:#"UserId"];
//redirect to login view
NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
[appsDelegate.window addSubview:[appsDelegate.login view]];
}
}
From what I can interpret from you question, which needs to be formatted and made coherent by the way, I believe that:
a) your #"UserID" value is not syncing with NSUserDefaults because you are not calling the -synchronize method. NSUserDefaults will update its in-memory key-value store, but will not write it to disk meaning that it's lost at an arbitrary time.
b) The fact that it is not going to the loginView could be to do with any few reasons, most likely that it is already a subview of your UIWindow. So, instead of reusing the login property in your app delegate, create a new instance variable of the View Controller, and set that as the rootViewController instead.
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:nil forKey:#"UserId"];
[defaults synchronize];
//redirect to login view
NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
LoginViewController *login = [[LoginViewController alloc] initWithNibName...];
[appsDelegate.window setRootViewController:nil];
[appsDelegate.window setRootViewController:login];
}
}
Swift:
From max_'s answer with some changes:
let objectsToSave: [String] = [obj1, obj2, obj3]
for key in objectsToSave {
NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}
let appsDelegate = UIApplication.sharedApplication().delegate
let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let newLoginVC: LoginViewController = storyboard.instantiateInitialViewController() as! LoginViewController
appsDelegate?.window!!.rootViewController = nil
appsDelegate?.window!!.rootViewController = newLoginVC
EDIT: The only changes I've made are just that I initialize newLoginVC through Storyboards instead of initWitName.
Make property of UINavigation controller and synthesize it, And write below code on logout button
AppDelegate * appDelegateObj =[[UIApplication sharedApplication] delegate];
login *loginObj = [[login alloc]initWithNibName:#"login" bundle:nil];
[appDelegateObj.window setRootViewController:nil];
navObj=[[UINavigationController alloc]initWithRootViewController:loginObj];
[appDelegateObj.window setRootViewController:navObj];

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?

Can I call presentModalViewController in viewDidLoad..?

In my iPhone app I have HomeViewController and ContentViewController. I am saving the values in ContentViewController by using NSUserDefaults
and based on saved values I will load the ContentView instead of HomeView when the app is restarted. if there r no values in the NSUserDefaults it displays the HomeView.
in HomeView I have some buttons..it's like this.. each button is for a book so in contentView all the page nos (in the bottom in a scroll view in ContentView) will be displayed if I click on a page no it displays the text in the above label of ContentView.if the user closes the app in contentView, the page no and book no will be saved...if the user clicks on home button all the information will be deleted.
In the Homeview im checking the NSUserDefaults, if it contains values it should display that exact page of that book
the following is the code...
//HomeViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentView" bundle:nil];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"...%d,%d,%d",[prefs integerForKey:#"Stage"],[prefs integerForKey:#"Stimulus"],[prefs integerForKey:#"Card"]);
if(!([prefs integerForKey:#"Stage"] ==0 && [prefs integerForKey:#"Stimulus"] ==0 && [prefs integerForKey:#"Card"] ==0)){
[contentViewController setCurrentState:[prefs integerForKey:#"Stage"]];
[contentViewController setCurrentStimulus:[prefs integerForKey:#"Stimulus"]];
[contentViewController setCurrentCard:[prefs integerForKey:#"Card"]];
[self presentModalViewController:contentViewController animated:YES];
}
}
but it's displaying the homeview.
Try using the method viewDidAppear shown below instead of viewDidLoad
- (void)viewDidAppear:(BOOL)animated
{
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentView" bundle:nil];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"...%d,%d,%d",[prefs integerForKey:#"Stage"],[prefs integerForKey:#"Stimulus"], [prefs integerForKey:#"Card"]);
if(!([prefs integerForKey:#"Stage"] ==0 && [prefs integerForKey:#"Stimulus"] ==0 && [prefs integerForKey:#"Card"] ==0))
{
[contentViewController setCurrentState:[prefs integerForKey:#"Stage"]];
[contentViewController setCurrentStimulus:[prefs integerForKey:#"Stimulus"]];
[contentViewController setCurrentCard:[prefs integerForKey:#"Card"]];
[self presentModalViewController:contentViewController animated:YES];
}
}