Stay Signed in option for iPhone app - iphone

I need to implement a "Stay Signed in" or "Remember Me" check box to my iPhone app. How do I implement this? How do I store the user id?
Help is highly appreciated,
Thanks,
VKS

#VKS
1
-(void)autologin:(id)sender
{
ischecked =!ischecked;
UIButton *check = (UIButton*)sender;
if(ischecked == NO)
[check setImage:[UIImage imageNamed:#"checkbox1.png"] forState:UIControlStateNormal];
else
[check setImage:[UIImage imageNamed:#"checkbox-pressed.png"] forState:UIControlStateNormal];
}
2
if(ischecked == YES)
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:mainDelegate.uName forKey:#"username"];
[standardUserDefaults setObject:mainDelegate.uPassword forKey:#"password"];
[standardUserDefaults synchronize];
}
and for retrieving the password/username
3
if(isChecked == YES)
{
NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
NSString *pass = [standard objectforkey:#"password"];
NSString *user = [standard objectforkey:#"username"];
}
if ([pass == nil] || [user == nil])
{
// Show the alert view that user is not valid.
}
else
{
// User is valid.
}

Since NSUserDefaults is not secure, i would recommend using iOS keychain to save password persistently.
look here: http://iosdevelopertips.com/core-services/using-keychain-to-store-username-and-password.html

Check whether check box is checked and if checked then
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:mainDelegate.uName forKey:#"username"];
[standardUserDefaults setObject:mainDelegate.uPassword forKey:#"password"];
[standardUserDefaults synchronize];
This will save your variables and while login check for the saved NSUserDefaults.
if (standardUserDefaults) {
//Here check for the values if there are any values then use the same and login
}
Check any NSUserDefaults tutorials on google, you will get the sample code.

Related

How can I create session?

I need to session. I couldn't find any thing about this issue. Therefore I used appdelegate global variable, but app global variable not save value long time.
I mean, my aim is login page. I don't want user to sign in many time in my app. How can I realize this approach?
save the data in NSUserDefaults,
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"username"];
[defaults synchronize];
NSString *username=[defaults objectForKey:#"username"] ;
You can use NSUserDefaults for this purpose.
Here's an example for you. Good luck!
- (void) createSession:(NSObject *anyObject) {
//write an object to NSUserDefaults with the key of "session"
[[NSUserDefaults standardUserDefaults] setObject:anyObject forKey:#"session"];
//persist the value in the store
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSObject*) getSession {
//get an object from NSUserDefaults with the key of "session"
return [[NSUserDefaults] standardUserDefaults] objectForKey:#"session"];
}
- (void) exampleUsage {
NSObject* mySessionObject = [self getSession];
if (mySessionObject != nil) {
//i have a session
} else {
//i do NOT have a session
}
}
You could check with NSUserDefaults
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if(![defaults boolForKey:#"login"])
{
/// view to login or signup what ever
}
else
{
/// user already logged in
}
You must use NSUserDefault To Login Window.
NSUserDefaults def=[NSUserDefaults standardUserDefaults];
[def setObject:delegate.txtfield1.text forKey:#"UserName"];
[def setObject:delegate.txtfield2.text forKey:#"Password"];
[def synchronize];
If you want to retrive the NSUSERDefault data used this code.
NSString *UserName=[defaults objectForKey:#"UserName"] ;
NSString *Password=[defaults objectForKey:#"Password"] ;
And For Checking the status
if(![def boolForKey:#"UserName"])
{
}
else
{
}
try this one might be helpful to you......

How to remove user defaults [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I reset the NSUserDefaults data in the iPhone simulator?
In my project i am saving some values in NSUserdefaults with different keys.And i have reset button in my app when i click that button values stored in user defaults should remove.Is there any way to delete those values without keys,and is addSuitedNamed: and removeSuitedName can use in this scenario.
NSUserDefaults * myNSUserDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [myNSUserDefaults dictionaryRepresentation];
for (id key in dict) {
//heck the keys if u need
[myNSUserDefaults removeObjectForKey:key];
}
[myNSUserDefaults synchronize];
or
[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];
With a selector being called on a button click you can achieve the same using
- (IBAction)btnResetUserDefaultsPressed:(id)sender {
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary* dictUserDefaults = [userDefaults dictionaryRepresentation];
for (id akey in dictUserDefaults) {
[userDefaults removeObjectForKey:akey];
}
[userDefaults synchronize];
}
For the second part of your question asked , You would certainly find this useful.
You can reset the values of NSUserDefault using resetStandardUserDefaults.
Check this code:
[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];
Also you can:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
Or you can use:
NSUSerDefaults *default = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [default dictionaryRepresentation];
for (NSString *key in [dictionary allKeys])
{
[default removeObjectForKey:key];
}
[default synchronize];

How to save User Name and Password in NSUserDefault?

I need to save User Name and Password in NSUserDefault. I am planning to place a round rect button in IB. On pressing of which the User name and Password would be saved in NSUserDefault, so that when user kills the application and tries to login again after some time, they do not need to enter their login details again.
Any help would be highly appreciated.
Thanks and best regards,
PC
For Saving Username and Password I will personally suggest to use Keychain as they are more safer than NSUserDefault in terms of security since Keychain stores data in encrypted form while NSUserDefault stores as plain text. If you still want to use NSUserDefault Here's the way
FOR SAVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:txtUsername.text forKey:#"userName"];
[prefs setObject:txtPassword.text forKey:#"password"];
[prefs synchronize];
FOR RETRIEVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedUsername = [prefs stringForKey:#"userName"];
NSString *savedPassword = [prefs stringForKey:#"password"];
Do not store plaintext passwords in user defaults, even if they are unimportant.
Use Keychain Services. The Generic Keychain Sample provides sample KeychainWrapper class, that can be used for reading and writing data into keychain with exactly the same setObject:forKey: interface as NSUserDefaults uses.
To Save:
[[NSUserDefaults standardUserDefaults] setValue:_Username forKey:#"Username"];
[[NSUserDefaults standardUserDefaults] setValue:_password forKey:#"password"];
[[NSUserDefaults standardUserDefaults] synchronize];
To Read:
NSString * _UserName = [[NSUserDefaults standardUserDefaults] stringForKey:#"Username"];
NSString * _password = [[NSUserDefaults standardUserDefaults] stringForKey:#"password"];
First off, I would not store the password in NSUserDefaults. I would rather use the keychain.
This is how you can save the username in NSUserDefaults:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:myString forKey:#"username"];
NSString* username = [standardUserDefaults objectForKey:#"username"];
On the other hand, an easy way to use the keychain is by using the SSKeychain class by Sam Soffes; in this case you would just say:
NSString* password = [SSKeychain passwordForService:#"YOUSERVICENAMEHERE" account:username];
[SSKeychain setPassword:password forService:#"YOUSERVICENAMEHERE" account:username];
You can store your credentials like this:
-(void)saveToUserDefaults:(NSString*)stringUserName pswd:(NSString*)strPassword
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:stringUserName forKey:#"UserName"];
[standardUserDefaults setObject:strPassword forKey:#"Password"];
[standardUserDefaults synchronize];
}
}
And you can retrive them like this:
-(NSArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
NSString *userName = (NSString*)[standardUserDefaults objectForKey:#"UserName"];
NSString *password = (NSString*)[standardUserDefaults objectForKey:#"Password"];
}
NSArray* credentials = [NSArray arrayWithObjects:userName, password, nil];
return credentials;
}
Cannot set NSUserDefaults field
Posted my code from link to stay assured that answer is still useful to community even if the above mentioned post is removed or deleted in future.
Code:
You can try this code. I am very sure that it will work for you.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *uid=#"1";
[defaults setObject:uid forKey:#"init_val"];
[defaults synchronize];
For Retrieving Data You Should Use The Following Code :
NSString *initVal=[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"];
OR
NSString *initVal=[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"];
EDIT:
If still it gives nil, then you can use the following code:
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"init_val"]];
OR
NSString *initVal=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"init_val"]];
In the above link, you will find my answer and replace "init_val" in my code there with your "username" and "password" as keys
Hope this helps you.
Good Answers are already given But here is a clean way of Saving/Loading/Deleting User Credentials in the keychain. Consider this, you can create a separate class and include the following code:
.h
#import <Foundation/Foundation.h>
#interface KeychainUserPass : NSObject
+ (void)save:(NSString *)service data:(id)data;
+ (id)load:(NSString *)service;
+ (void)delete:(NSString *)service;
#end
.m
#import "KeychainUserPass.h"
#implementation KeychainUserPass
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass,
service, (__bridge id)kSecAttrService,
service, (__bridge id)kSecAttrAccount,
(__bridge id)kSecAttrAccessibleAfterFirstUnlock, (__bridge id)kSecAttrAccessible,
nil];
}
+ (void)save:(NSString *)service data:(id)data {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}
+ (id)load:(NSString *)service {
id ret = nil;
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
CFDataRef keyData = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
#try {
ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
}
#catch (NSException *e) {
NSLog(#"Unarchive of %# failed: %#", service, e);
}
#finally {}
}
if (keyData) CFRelease(keyData);
return ret;
}
+ (void)delete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}
#end

NSUserDefaults, credentials removal on uncheck iPhone

I am using below code for for saving the username password, credentials saved properly but the issue is when I again run the application, it shows the credentials in textfields but checkbox remains empty (i am using images to show the box checked and unchecked).
My questions are:
1. How can i save the state of checkbox if it is checked or unchecked and
2. If it is unchecked how can i remove the credentials from nsuserdefaults.
- (IBAction)checkboxButton:(id)sender{
if (checkboxSelected == 0){
[checkboxButton setSelected:YES];
NSString *user = [userNameField text];
NSString *passwd = [passwordField text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:user forKey:#"Username"];
[defaults setObject:passwd forKey:#"Password"];
[defaults synchronize];
NSLog(#"Data Saved");
checkboxSelected = 1;
} else {
[checkboxButton setSelected:NO];
checkboxSelected = 0;
//Saving Username Password in file
}
}
thank you ... :)
Well you can save the state of the checkbox in the NSUserDefaults.
To read do the following.
BOOL isChecked = [[NSUserDefaults standardUserDefaults] boolForKey:#"loginCheckBox"];
It will return NO (false) if it is not set.
To set the state:
[[NSUserDefaults standardUserDefaults] setBool:checkboxButton.selected forKey:#"loginCheckBox"];
To remove the values from the NSUserDefaults just set the properties to nil:
[defaults setObject:nil forKey:#"Username"];
[defaults setObject:nil forKey:#"Password"];
Also I can strongly advice you to store the password in the keychain.
since all the data saved in NSUserDefaults is stored plain text.
You can use the easy to SSKeyChain for accessing keychain api more easily.
for saving checkmark state you have to maintain a variable which has to be saved and read again to set the last state of checkmark and for removing values from NSUserDefaults : you can use:
removeObjectForKey method

NSUserDefaults doubts

#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btnTwitter setTitle:username forState:UIControlStateNormal];
}
I have this code for displaying username for twitter ,and it works well,but when i navigate to another page and came back the title username of the button disappears,i know we have to set a NSUserDefault value in viewwillapper for checking the username exists or not.But i didn't know how to handle the nSUserDefault,if anyone have an idea to solve this issue please help me.
Thanks in advance.
EDIT:
- (void)viewWillAppear:(BOOL)animated{
//Sets up the NSUserDefaults
//Sets up the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Checks if there is a saved User Name
if([defaults objectForKey:#"kTwitterUserName"])
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
[_btnTwitter setTitle:username forState:UIControlStateNormal];
else
{
}
this is how my viewwillappear lokks
and
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btnTwitter setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults synchronize];
}
this is how my twitermethod looks like
NSUserDefaults are very simple to work with. They are kind of like a dictionary, you set an object and a key. So to do what your trying to do, you can use something like the following:
//This just sets up the defaults - similar to allocating a dictionary
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Then to set an object in your defaults, you set an object/key pair like this:
[defaults setObject:username forKey:#"kTwitterUserName"];
It is important to call this method at some point: [defaults synchronize];. This explicitly saves the defaults. So you might as well do it immediately after you set the username key.
Then to read the saved username:
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
Your oAuth Method should look like this:
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
//Any thing else you want to do - NSLogs, etc.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults synchronize];
}
So your viewWillAppear will look something like this:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//Sets up the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Checks if there is a saved User Name
if([defaults objectForKey:#"kTwitterUserName"]) {
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
} else
//Do something else because there is no saved username
NSLog(#"no username saved");
}
Let me know in a comment if you need any clarification.
You're correct in the aspect you'll want to save this somehow, and NSUserDefaults will work fine for this. Save and read samples are below:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"username" forKey:#"UsersUsername"];
// reading an NSString
NSString *theString = [prefs stringForKey:#"UsersUsername"];
http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/ for more details