Can I change the apps view based on if a file has been saved? - iphone

Please help! I'm a newbie to programming and I'm having the following trouble. I am trying to write my first iphone app and I would like it to do the following.
When the app launches user enters name, presses button and goes to new view. Their name is saved to file and used through out the app. That much I have managed.
I would like the app to check to see if there is a saved file when it is launched and go directly to second view instead of the first view. I'm have search for days looking for an answer and I'm still not sure how to do this.
At the risk of seeming stupid do I use an IF statement and how do I write it. Please help.
Thanking you in advance.

You have to use NSUserDefaults for storing the user name and pass words. If you want to store more data's, have to use plist(Documents Directory) or core data or SQLite.
// Store the data
[[NSUserDefaults standardUserDefaults] setObject:#"yourPasswordString" forKey:#"YourKey"];
// Retrieve the data
NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:#"YourKey"];
Once you retrieved the data, you have to check the conditions like,
if(passWord == nil)
{
//load first view
}
else
{
// load second view
}
Thanks!

if you're using NSUserDefaults to save it then all you have to do is try reading the value into a string, then check if it is nil, if it is, then the files isn't there and you would load your first view, if it was, then load your second view.
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"yourKey"];
if(tempStr == nil)
{
//load your first view
}
else
{
// load your second view
}
You need to read your key back out in order to test if it is nil, the way you are doing this, you will never be nil and will always use the else choice, you need to set your object elsewhere, probably in the if statement.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if (tempStr == nil || [tempStr isEqualToString:""])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
ClubSearchViewController *CSearch = [[ClubSearchViewController alloc]initWithNibName:#"ClubSearchViewController" bundle:Nil];
[self presentModalViewController:CSearch animated:YES];
}
else
{
SearchMenu *SMenu = [[SearchMenu alloc]initWithNibName:#"SearchMenu" bundle:nil];
[self presentModalViewController:SMenu animated:YES];
}
}
-(IBAction)LogOutButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"" forKey:#"UserName"];
[prefs synchronize];
}

Related

NSUserDefaults - storing and retrieving data

I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.
I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.
here's the code that Im displaying the NSUserDefaults stored info on a UILabel:
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
if someone could point me in the right direction that would be great,
thanks
Put this text in
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTextFieldKey"];
NSLog(#"Value from standardUserDefaults: %#", aValue);
NSLog(#"Label: %#", myLabel);
myLabel.text = aValue;
}
And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults
When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:
[[NSUserDefaults standardUserDefaults] synchronize];
This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.
Do not forget the use synchronize when you set some value
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:#"KEY_NAME"];
[defaults synchronize];
Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue = [defaults objectForKey:#"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : #"No Value";
Hope it helps
In Swift we can do it following way:
To save value:
let defaults = UserDefaults.standard
defaults.set(YOUR_VALUE, forKey: "YOUR_KEY_NAME")
To get value:
let defaults = UserDefaults.standard
let data = defaults.objectForKey("YOUR_KEY_NAME")
For more details visit:
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults

Saving and Retrieving UILabel value with NSUserDefaults

I trying to save UILabel value to NSUserDefaults. I did IBAction with this code:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:#"result"];
[prefs synchronize];
}
Then, I connect it to button with Touch Up Inside.
What log shows after I pressed the button:
result = 0;
When I pressed a second time, then it works.
result = "28.34";
What I'm doing wrong and how can I retrieve a result?
EDIT
With this code I display result in log. I put it to same action.
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
Your code looks correct, so the issue is probably not the function you posted but rather the code that contains your NSLog. You might be logging the value in a way that misses the first time it gets set.
Your log statement should be
NSLog(#"%#",[[NSUserDefaults
standardUserDefaults]
objectForKey:#"result"]);
This should be after you set the object in NSUserDefaults.
Add this to your applicationDidFinishLaunching in appDelegate or in init method in viewController(you have to create one) :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(prefs == nil)
{
[prefs setObject:#"anything" forKey:#"result"];
[prefs synchronize];
}

NSUserDefaults problem

I have this in my app delegate applicationDidFinishLaunching method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"AcceptTC"] == nil){
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:#"NO" forKey:#"AcceptTC"];
[defaults registerDefaults:appDefaults];
}
and I have this in my RootViewController viewDidLoad method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if(![defaults boolForKey:#"AcceptTC"]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Notice" message:#"By using this application you agree to be bound by the Terms and Conditions as stated within this application." delegate:self cancelButtonTitle:#"No Deal" otherButtonTitles:#"I Understand",nil];
[alert show];
[alert release];
}
and my alert view delegate does this:
if(buttonIndex == 0){
exit(0);
}
else{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"YES" forKey:#"AcceptTC"];
}
However when I click "I understand" (button index 1) and then restart the application I still see the alert view! Even though I've definiely set the value to YES.
I have no idea how to change this. :( I only want it to show the first time a user starts the application - i don't want to keep showing it every time they want to use it.
Thanks
In my application I'm using NSUserDefaults with a bool, works fine.
When the first ViewController loads, it will do:
BOOL terms = [[NSUserDefaults standardUserDefaults] boolForKey:#"termsaccepted"];
if (!terms) {
[self presentModalViewController:disclaimerViewController animated:YES];
}
Within the disclaimer view, after the button has been tapped:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"termsaccepted"];
[[NSUserDefaults standardUserDefaults] synchronize];
I think you're missing the "synchronize" part. However I find using a bool more streamlined, too.
Maybe you need to call synchronize on the defaults to save the changes to disk?
Concering registerDefaults:
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.
// Load default defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary \
dictionaryWithContentsOfFile:[[NSBundle mainBundle] \
pathForResource:#"Defaults" ofType:#"plist"]]];
Code taken from this SO answer.
Another blog article about NSDefaults:
http://retrodreamer.com/blog/2010/07/slight-change-of-plan/

NSUserDefaults doesn't save

i'm trying to save some informations in an iphone/ipad app.
The problem is that it works but if i close the app (with the home button on the simulator or closing with cmd+q) the informations become lost!
this is my code (and, if you see, i used "syncronize")
- (IBAction)choose1{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose1" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)choose2{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose2" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
else if (var == #"choose2"){
[self pushViewController:view2 animated:YES];
}
}
I don't understand why :(
When comparing strings, you should use the isEqualToString method, ie:
if ([var isEqualToString:#"choose1"]){
Otherwise you are comparing actual objects rather than their contents.
I am not entirely sure, but maybe it is saving your defaults and the error is located somewhere else. I am thinking about your "openView" method:
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
/** you are comparing to "choose1" here as well. **/
else if (var == #"choose1"){
[self pushViewController:view2 animated:YES];
}
Another possibilty might be that you never call your choose1() or choose2() methods?
This would explain why the value is never changed.
Despite from these 2 possibilites I think there is no error in the code you use to change the UserDefaults.
Hope this helps.
Regards,
Gjallar
ah, i'm sorry: i'm italian so i used the word "choose" with the italian translation "scelta".
Here i translated in english and i wrote "choose1" but in my code i used "choose2" (or "scelta2" :P)
for the other possibility (that i've never called the function choose1() or choose2() )... no, i've called, of course!

Best way to check if an iPhone app is running for the first time

I want to check if my iPhone app is running for the first time. I can create a file in the documents folder and check that file to see if this is the first time the app is running, but I wanted to know if there is a better way to do this.
I like to use NSUserDefaults to store an indication of the the first run.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"])
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can then test for it later...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"firstRun"])
{
// do something or not...
}
Ok what confuses the hell out of me about User Defaults.
WHERE are they stored?
you dont care it varies per iOS/Mac.
you just getVALUE by KEY
setVALUE by KEY + synchronize
iOS/Mac does the rest.
This is the common use case:
Checking for the existence of a value e.g firstRun.
The first time it will NOT EXIST so usually followed by setting the value.
2nd Run
- on next loop it does exist and other use case/else stmt is triggered
---- .h
#interface MyAppDelegate : UIResponder <UIApplicationDelegate>
//flag to denote if this is first time the app is run
#property(nonatomic) BOOL firstRun;
------ .m
#implementation MyAppDelegate
#synthesize firstRun = _firstRun;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//==============
//Check to see if this is first time app is run by checking flag we set in the defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"]){
//flag doesnt exist then this IS the first run
self.firstRun = TRUE;
//store the flag so it exists the next time the app starts
[defaults setObject:[NSDate date] forKey:#"firstRun"];
}else{
//flag does exist so this ISNT the first run
self.firstRun = FALSE;
}
//call synchronize to save default - where its saved is managed by iOS - varies by device and iOS/Mac
[[NSUserDefaults standardUserDefaults] synchronize];
//TO TEST: delete the app on the device/simulator
//run it - should be the first run
//close it - make sure you kill it and its not just in the background else didFinishLaunchingWithOptions wont be called
//just applicationDidBecomeActive
//2nd run it should self.firstRun = FALSE;
//=============
//NOTE IMPORTANT IF YOURE ROOTVIEWCONTROLLER checks appDelegate.firstRun then make sure you do the check above BEFORE setting self.window.rootViewController here
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
return YES;
}
---- USING THE FLAG
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.firstRun){
NSLog(#"IS FIRST RUN - Do something: e.g. set up password");
}else {
NSLog(#"FPMyMusicScreenViewController: IS NOT FIRST RUN - Prompt for password");
}
The examples above confused me a bit as they show how to check for it the first time but then mention how to 'check for it later' in the same comment.
The problem is when we find it doesnt exist we immediately create it and synchronize.
So checking for it late actually mean when you RESTART THE APP not in same run as first run.
In your app delegate register a default value:
NSDictionary *defaultsDict =
[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithBool:YES], #"FirstLaunch", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
[defaultsDict release];
Then where you want to check it:
NSUserDefaults *sharedDefaults = [NSUserDefaults standardUserDefaults];
if ([sharedDefaults boolForKey:#"FirstLaunch"]) {
//Do the stuff you want to do on first launch
[sharedDefaults setBool:NO forKey:#"FirstLaunch"];
[sharedDefaults synchronize];
}
You can implement it with the static method below. I think it's better since you can call this method as many times as you like, unlike the other solutions. enjoy: (Keep in mind that it's not thread-safe)
+ (BOOL)isFirstTime{
static BOOL flag=NO;
static BOOL result;
if(!flag){
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"hasLaunchedOnce"])
{
result=NO;
} else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"hasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
result=YES;
}
flag=YES;
}
return result;
}
You can use a custom category method isFirstLaunch with UIViewController+FirstLaunch.
- (BOOL)isFirstLaunch
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"kFirstLaunch"]) {
return YES;
}
else {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"kFirstLaunch"];
[[NSUserDefaults standardUserDefaults] synchronize];
return NO;
}
}
And when you need to use it in controller
BOOL launched = [self isFirstLaunch];
if (launched) {
//if launched
}
else {
//if not launched
}
Use NSUserDefaults. If the sharedDefault has a key for your app, its run before. Of course, you'll have to have the app create at least one default entry the first time the app runs.
Swift:
var isFirstLaunch: Bool {
get {
if (NSUserDefaults.standardUserDefaults().objectForKey("firstLaunchDate") == nil) {
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "firstLaunchDate")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}
Another tip:
When using NSUserDefaults, these settings will be wiped if the app is ever deleted. If for some reason you require these settings to still hang around, you can store them in the Keychain.