NSUserDefaults doubts - iphone

#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

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

problem in saving a value in iphone

when i enter a value in the iphone simulator and press the save button it only keeps the value until the simulator is running. and when i restart the simulator and press the load button it shows an earlier value entered by me.i.e, it is not able to keep the new value and keeps only old value.
i am using following loops for saving a file and loading a file.
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
[king setObject:noc.text forKey:#"save"];
}
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = [NSString stringWithFormat:tempstring];
NSUserDefaults *king=[NSUserDefaults standardUserDefaults];
NSString *tempstring1 =[king stringForKey:#"save"];
noc.text = [NSString stringWithFormat:tempstring1];
}
// Your code
NSUserDefaults *king= [NSUserDefaults standardUserDefaults];
[king setObject:bookmarks forKey:#"Bookmarks"];
// saving it all
[king synchronize];
-(IBAction) save{
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
[sinner setObject:serverIP.text forKey:#"load"];
[sinner setObject:noc.text forKey:#"save"];
[sinner synchronize];
}
This should save the contents. You dont need two separate userdefaults. To load them you can try
-(IBAction) load {
NSUserDefaults *sinner=[NSUserDefaults standardUserDefaults];
NSString *tempstring =[sinner stringForKey:#"load"];
serverIP.text = tempstring;
NSString *tempstring1 =[sinner stringForKey:#"save"];
noc.text = tempstring1;
}
Hope this helps

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