iphone Settings application persist data - iphone

In my app I'm using an NSUserDefaults object to store the username, password and server URL in the built-in Settings app. If there is no data saved, the user is presented a login interface and upon succesful login the username and password are saved. Then in my app I have a view which displays this information, but the text is missing as if the data hasn't been saved to the Settings yet. Here's the code:
...
NSUserDefaults* appSettings = [NSUserDefaults standardUserDefaults];
[appSettings setObject:username forKey:USERNAME];
[appSettings setObject:password forKey:PASSWORD];
if ( [appSettings synchronize] ) {
// display an alert with a positive message
} else {
// display an alert with a negative message
}
So, after logging in the positive message is displayed, but when I fetch the data again there is nothing there, unless I restart the app.
What do I need to do to save the data immediatly, or at least before another view controller needs to read the settings?

The NSUserDefaults object stores its data in memory, and is a global object (to your application, anyway). Thus, anything you store in there should be immediately available to anything that tries to access it afterwards. You don't need to call synchronize here. If you're not getting your data, you should check the order of your calls to make sure they're being called when you think they are.

Related

iOS: How to authenticate a user after login (for auto login)?

I'd like to use an auto-login function. So when the user opens the app, he gets delegated to a "login screen". When he logged in successfully he should be directed to his account. I call this the "account screen". Now when the user restarts the app, he should directly get directed to his account, without seeing the "login screen".
The login function already works fine in my project (username and password are saved in UserDefault), but every time I close the app, I have to login again. So my question is: How do auto login the user? Or better said: How do I check if the data (saved in UserDefault) is the same as in the database (MYSQL)?
For the first time when the user login, you save the user
credentials in iPhone's keychain.
When the app is opened again, you check whether user credentials are
present in keychain and if yes, you code should call the login
logic and do auto login and go to screen after login screen. If no,
then you should show login screen. You can do this logic in AppDelegates applicationDidFinishLaunching.
Whenever user clicks the logout button, remove user credentials from
keychain first, and go back to login controller.
Simply you add login credentials to keychain when user logs in and only remove it once user clicks the logout button. If user quits the app without logout then the credentials will still be in keychain and you can retrieve them when user returns to the app.
EDIT: I think I must add one more thing..If your login logic takes time (like you login using web request or something), put the login logic code in your Login ViewController rather than ApplicationDelegate, and use any Activity Indicator during auto login process.
EDIT : I edited the entire answer, replaced NSUserDefault with Keychain. This thread explains why.
While saving Username and Password, it is highly advised to save in Keychain rather than the NSUserDefaults. Refer this post for a better understanding.
To answer the question: if you want to auto-login with keychain data, use the free framework "SFHFKeychainUtils". It saves username, password and servicename in keychain. if you want to retrieve it, just save the username in NSUserDefaults and you can get the password with ease.
Here we go:
SiFi HiFi Framework: https://github.com/ldandersen/scifihifi-iphone/tree/master/security
SiFi Hifi Framework (ARC compatible): https://stackoverflow.com/a/10348964/1011125
How to use SFHFKeychainUtils: http://gorgando.com/blog/technology/iphone_development/simple-iphone-tutorial-password-management-using-the-keychain-by-using-sfhfkeychainutils
I used a combination of NSUserDefaults and SSKeychain. I used NSUserDefaults to store the username nad SSKeychain to store the password.
This is the code I used to save the credentials
NSString *user = self.username.text;
NSString *password = self.pass.text;
[SSKeychain setPassword:password forService:#"achat" account:user];
NSUserDefaults *dUser = [NSUserDefaults standardUserDefaults];
[dUser setObject:user forKey:#"user"];
[dUser synchronize];
This is the code I used to retrieve the credentials
NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults];
NSString *savedUser = [eUser objectForKey:#"user"];
if (!savedUser) {
UIAlertView *uhoh = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Please enter your username and password." delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[uhoh show];
}
else {
NSString *savedPass = [SSKeychain passwordForService:#"achat" account:savedUser];
self.username.text = savedUser;
self.pass.text = savedPass;
}

How to implement log in and Log out in an app

I am using XCode4 for development.
In my applicaion I need login to a website to get the information. then by using that I have to perform some task.
I am accessing the website by REST service call. After the ASIHttpRequest passed
I am setting the user name & password like this.
[request setuserName:#"usernameString"];
[request setpassword:#"Passwordstring"];
But I am not aware of whether any session created or not.
So at the time of log out I only redirect the controller to log in screen & made the userName and password field blank.
But after logout it is taking wrong user name and password to login again.
My question:
Whether I have to create a session while log in and time out the session at the time of log out. How to do that?
In iphone application how Log in & Log out generally done?
you best choice will be using NSUserDefaults class, example:
// saving your data.
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:myUsername forKey:#"username"];
// retrieve your data
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *username = [standardUserDefaults objectForKey:#"username"];
you can also use NSUserDefaults to store the Log in status of the current session by for example storing a Boolean key for isLoggedIn key
[standardUserDefaults setBOOL:TRUE forKey:#"isLoggedIn"];
When the user wishes to log out just set the value to FALSE to offer the user the log in view again as if this is the first time the user is using the app.
You don't need to set timeout session for the logged in users, unless your design or the requirements said so, but you can also do that easily by using NSUserDefaults by storing the date and time of the user log in, and check that continuously to validate the session timeout, but I don't recommend to do such a thing, but everything is possible here.
Thanks all. This problem is solved.
At the time of log in, ASIHTTPRequest is creating a cookie object on successful log in. If a user did not spend 1 minute inside the application and came out by tapping sign out. After that it was taking any userId and password (garbage data) to login again. It happened because the previous cookie was taking care for that.
But, now at the time of sign out, I am deleting the cookie which is created at the time of log in.
I have added below code in sign out:-
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *each in [[[cookieStorage cookiesForURL:YOUR_URL] copy] autorelease])
{
// NSLog(#"cookie deleted==%#",each);
[cookieStorage deleteCookie:each];
}
AhmadTK's answer is fine, just a couple of points:
Always make sure you call [standardUserDefaults synchronize]; after setting values.
Initiate a check of the isLoggedIn item when the application starts, and if false, present the login screen for the user
Handle the logout process in the reverse (set the isLoggedIn value to NO)

How can i store data into a text file and retrieve it when the application launches again in iphone application development?

At first of all i want to say that i am newer as an iPhone application developer.So please help me. Now, My problem is, I want to make a text file in my iPhone app.If I explain it then I will say that...
When user will login in my app then he/she will give username and password, Now i want to store these data in the text file and text file will store in the documentsDirectory, when this user again lunch the application then automatically he will able to excess the app without any authentication checking if he/she does not logout from the application first time.
1) 1st person --> login [username & password] --> store username and pass into text file because new user --> enjoy application -->logout.
2) 2nd person --> login [username & password] --> store in text file into text file because new user --> enjoy application --> did not logout.
3) 2nd person again ---> will not give username and password directly he/she have to use the application -->logout.
4) 1st person now ---> login [username & password] and check by saved reading text file ---> enjoy application --> logout.
5) 2nd person now ---> login [username & password] and check by saved reading text file ---> enjoy application --> logout.
Now, my question is how can i do this full process.Can i do this using NSUserDefaults standardUserDefualts or i need to make a text file for storing username & password??
Yes you can store simple bits of data like these in standardUserDefaults.
I assume that you will check user identity though.
e.g.what if user 1 logs in but does not logout and then user2 launches the app?
Personally I would only store the username if you plan for more than one person to access the app on a specific device and I would require the password each time.
set:
[[NSUserDefaults standardUserDefaults] setObject:userNameStr forKey:userName];
[[NSUserDefaults standardUserDefaults] synchronize];
get:
userNameStr = [[NSUserDefaults standardUserDefaults] objectForKey:userName];
I would think about storing username/password in the keychain. It is more secure and you won't have to worry about that information getting hacked out of the user defaults plist. If you still want to use a username and password, consider hashing it before storing it. Then if that information gets out (unlikely, but still possible) it won't mean anything to them.
You can actually view the contents of your user defaults from Organizer, the information is just stored as plain text there, so it is not recommended to use this as a way to store username and password.

How to use NSUserDefaults for creating the auto login settings for application

I know this very regular question But i didn't get that's way ask here I hope people will me out .
I have application which have the login page .And when ever I login I get Token_ID from server .I get this TokenID with help of JSON.
But I want to add the Auto Login function to my application .For that My application look like this
It has the two text field (username and password)
one check box for auto login And login button
I need when ever user click on the check box which is for auto login It must store TokenID in application and when I close my application .And start the application again It must not ask for login me again.It start the same application with same TokenID which I store for that user not a new one .And if I click the log out button it must logout from application And release the TokenID from my application .And after that if start the application it must ask for login with out that it must not go further in application
For that I do R&D from two days .And I found that I must use the NSUserDefaults for storing the TokenID which I am getting at the time of login .I want know how can I store the TokenID
into application and How can check it out the user logout or not .And if user not logout it start the application.And if user logout than it must ask for login to start the application
OR is that any idea please give And explain me
Thank you
First result at google for "NSUSerDefaults Example"
On logout just overwrite the keys with nil and check on starting of the app if the key is nil
you can save username information
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:#"username"];
[standardUserDefaults synchronize];
}
}
if you have username information on NSUserDefaults, you can get your username information
-(NSString*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:#"username"];
return val;
}

Check if app has been purchased

I am a beginner; I am trying to solve this but am unable to do so.
I have created an app that displays a few options in a table. When the user taps the cell the details of selected option is shown on another page (details are stored in a plist file).
What I want to do is to set it up so that if the user has purchased the app then only the details should be visible, but if the user has not purchased it, the user should be prompted to do so.
I have created a product ID for iTunes Connect and also created a testing account to test the app.
My problem is with the code: how should i check if user has already made the purchase?
Using NSUserDefaults is the easiest solution.
After a successful purchase:
[[NSUserDefaults standardUserDefaults]
setObject:#"purchased"
forKey:#"myPaidItem"];
[[NSUserDefaults standardUserDefaults]
synchronize];
And when you need to check if the user has purchased the item:
NSString* isPurchased =
[[NSUserDefaults standardUserDefaults]
stringForKey:#"myPaidItem"];
if ([#"purchased"
compare:isPurchased]==NSOrderedSame) {
........ }
Hope that helps
you have to store this information in appContext as a bool if the transaction is OK , boo= true
and when he want to buy another time you hve to check the value of boo wich is stored in app Context