NSUserdefaults for multiuser - iphone

In my application, I am using a login form to enter into the application, also using NSUserDefaults to store user preferences, for example:
[storeData setObject:self.loginField.text forKey:#"USEREMAIL"];
[storeData setObject:self.PasswordField.text forKey:#"PASSWORD"];
Like I stored, if a new user logs in the NSUserDefaults stored value will be changed. But I want both preferences (ex:new userid and old userid as well as password). So please explain how to store multiple values for same key?

One way to solve this would be to store a NSDictionary with UserIDs as keys and the passwords as values.
Another option is to use Keychain as it specifically designed for this kind of thing and is also more secure.

Create a Global NSMutableArray and add above details in NSDictionary Objects and Store all Objects in array.This way you will have all user objects.You can get it whenever you want.

first of all create global array with AppDelegate class, for example..
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"arrScheduleDates"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
arrScheduleDates = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
arrScheduleDates = [[NSMutableArray alloc] init];
} else {
arrScheduleDates = [[NSMutableArray alloc] init];
}
[arrScheduleDates retain];
after that when you want to store the new record then get all record from arrScheduleDates array and after that add the new record and after that store like whole array like above..
i hope you understand and its helpful for you...
:)

The absolute easiest way to meet your requirements is to use the user's email address (assuming they're all unique) as the storage key for your dictionary, and the password as the value.
If you need to store more than the password, then the value of the key would be another dictionary with keys and values for the user.
An example of the simple case would look similar to :
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *storedUsers = [userDefaults objectForKey:#"userData"];
if (nil == storedUsers) storedUsers = [NSDictionary dictionary];
NSMutableDictionary *mutableStoredUsers = [NSMutableDictionary dictionaryWithDictionary:storedUsers];
NSString *userPassword = [self.PasswordField.text copy]; //add autorelease if you aren't using ARC
NSString *userEmail = [self.loginField.text copy]; //add autorelease if you aren't using ARC
if (nil != userEmail)
{
[mutableStoredUsers setObject:userPassword forKey:userEmail];
}
[userDefaults setObject:[NSDictionary dictionaryWithDictionary:mutableStoredUsers] forKey:#"userData"];
[userDefaults synchronize];

first download and import files of given link
https://github.com/ldandersen/scifihifi-iphone/tree/master/security
then where u want to store user preferences write this code
[SFHFKeychainUtils storeUsername:loginField.text andPassword:PasswordField.text forServiceName:#"dhaya" updateExisting:YES error:&error];
where u want password write this code
NSString *password = [SFHFKeychainUtils getPasswordForUsername:loginField.text andServiceName:#"dhaya" error:&error];
NSLog(#"passwordpassword %#",password);
this will working great....

Related

How to retrive data from document directory when application start?

I have created application that record sound and display that sound file in tableview. In that application when sound is recorded than it's filepath will store in a array , which array i use to populate my tableview. But my problem is that when i close the application then my array will be empty , and i lost my recorded file.
So now how can i get my recorded file when i open my app second time. I am storing sound file in document directory.
Store array in NSUserDefaults. Retrive and Store the array in NSUserDefaults .. see the example of NSUserDefaults
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *yourArray;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"yourArray"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
yourArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
yourArray = [[NSMutableArray alloc] init];
} else {
yourArray = [[NSMutableArray alloc] init];
}
[yourArray retain];
after that when you want to insert Data in this UserDefaults Use Bellow Code...
[appDelegate.yourArray addObject:yourDataString];///set your value or anything which you want to store here...
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.yourArray];
[appDelegate.userDefaults setObject:data forKey:#"yourArray"];
[appDelegate.userDefaults synchronize];
i hope this help you...

How to count the number of objects save into NSUserDefault?

I have a question about NSUserDefault. Currently, i wanna write a function which save the favorite school into a list.
I have school name and school Id. So each time I save, school name + school id will be 1 dictionary object.
Then I save into NSUserDefault base on the id as key. I want to know the number of objects I saved into NSUserDefault. Or How can I get all of the objects out of NSUserDEfault since each of my key is different. Please help me out. below is my code:
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *schools = [[NSMutableDictionary alloc] init];
[schools setObject:schoolName forKey:kSchoolName];
[schools setObject:schoolID forKey:kSchoolID];
[userDefault setObject:schools forKey:schoolID];
How many objects are you storing? Maybe this isn't the best use for NSUserDefaults.
But to directly answer your question:
NSUInteger count =
[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] count];
You would want to use a same key to store your schools dictionary.I mean,
[userDefault setObject:schools forKey:#"Schools List"];
Then to retrieve it
NSDictionary *schools = [userDefault ObjectforKey:#"Schools List"];
[[schools allkeys]count];
That will give you the count.

How To Save Data For Bookmarks?

I'm creating a very simple bookmarks menu for my app. I just need to save 3 strings for each object.
I was thinking of using core data but I don't want this to be connected with my core database for various reasons. Therefore what other easy options do I have? NSUserDefaults or .plist?
I just need to save the 3 strings for each object then load them into a table view to be viewed.
I'd recommend NSUserDefaults - is certainly easier. I tend to only use plist files for static data that I want to be editable as the developer, but from the application want it to be read-only (such as coordinates for objects on an embedded map image).
From your description, you would probably want to store an NSArray containing NSDictionary.
// Get the user defaults object
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// Load your bookmarks (editable array)
NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
NSArray *bookmarksLoaded = [userDefaults arrayForKey:#"bookmarks"];
if (bookmarksLoaded != nil) {
[bookmarks initWithArray:bookmarksLoaded];
} else {
[bookmarks init];
}
// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:#"value" forKey:#"name"];
[bookmark setValue:#"value" forKey:#"description"];
[bookmark setValue:#"value" forKey:#"code"];
[bookmarks addObject:bookmark];
// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
[userDefaults synchronize];
// Memory cleanup
[bookmarks release];

How to keep given password in mgtwitterengine api

I want to keep password which is given by user in a variable. Where to get password value. I look in code but it is containing only username. I am using MGTwitterengine api in my application. Here is the function which is printing data on console.
-(void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
NSLog(#"uset sername %# and password %#",newUsername,newPassword);
...
}
I debug in all function but I saw this function is running after loggedin. But this is printing null in password value although username is printing well. Actually I I have to trace all tweet value of user. I went through MGTwitterEngine. There is a block of code but it is necessary to write username and password.
Here is the code
MGTwitterEngine *twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
[twitterEngine setUsername:#"username" password:#"password"];
// Get updates from people the authenticated user follows.
NSString *connectionID = [twitterEngine getFollowedTimelineFor:nil since:nil startingAtPage:0];
Please help me how to keep password ?
Read the developer documentation, it provides all the info you need for something as easy as this. Back to the question, there're a couple of ways how you can save this data.
NSUserDefaults: You can save the username and password using this class like this:
[[NSUserDefaults sharedUserDefaults] setObject:username forKey:#"username"];
[[NSUserDefaults sharedUserDefaults] setObject:username forKey:#"password"];
[[NSUserDefaults sharedUserDefaults] synchronize];
Once you need this data again, call it:
NSString*username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString*password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
OR:
NSDictionary: If you don't want to rely on NSUserDefaults, you can save the login data in a NSDictionary and save it to your sandbox. This works like this:
NSMutableDictionary*loginDictionary = [[NSMutableDictionary alloc] init];
[loginDictionary setObject:username forKey:#"username"];
[loginDictionary setObject:password forKey:#"password"];
[loginDictionary writeToFile://Your Path Here atomically:NO];
[loginDictionary release];
Then, once you need the data again, read from file:
NSMutableDictionary*loginDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile://Your Path];
NSString*username = [loginDictionary objectForKey:#"username"];
NSString*password = [loginDictionary objectForKey:#"password"];
[loginDictionary release];
Hope it helps!

NSUserDefaults won't save NSDictionary

I'm writing an application which uses NSUserDefaults as the data storage mechanism, and am hitting a problem when trying to save data (that conforms to the Property List protocols):
+ (BOOL)storeAlbum:(Album *)album
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *albums = (NSMutableDictionary *)[prefs objectForKey:#"my_adventure_book_albums"];
NSLog(#"Existing albums: %#",albums);
if (!albums)
albums = [NSMutableDictionary dictionaryWithObject:album forKey:#"album"];
else
[albums setObject:album forKey:#"album"];
NSLog(#"%#",album);
[prefs setObject:albums forKey:#"my_adventure_book_albums"];
return [prefs synchronize];
}
I get this output:
2010-06-29 17:17:09.929 MyAdventureBook[39892:207] Existing albums: (null)
2010-06-29 17:17:09.930 MyAdventureBook[39892:207] test
2010-06-29 17:17:09.931 MyAdventureBook[39892:207] *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '{
album = test;
}' of class 'NSCFDictionary'.
The description method of Album looks like:
- (NSString *)description
{
// Convert to a NSDictionary for serializing
if (!title) title = #"";
if (!date) date = [NSDate dateWithTimeIntervalSinceNow:0];
if (!coverImage) coverImage = #"";
if (!images) images = [[NSArray alloc] initWithObjects:#"",nil];
//NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:title,date,coverImage,images,nil] forKeys:[NSArray arrayWithObjects:#"title",#"date",#"coverImage",#"images",nil]];
//NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:title,nil] forKeys:[NSArray arrayWithObjects:#"title",nil]];
//return [dict description];
return #"test";
}
All of the commented-out lines have the same result, so I just decided to see if the NSString "test" would work, which it (of course) doesn't.
But the object you put inside the dictionary, an Album* is most likely not a property list object, is it? Every object, all the way down, needs to be a property list object for this to work. A description method isn't good enough to make this happen.
As a workaround, you can use NSCoding and an NSKeyedArchiver to write out your dictionary to an NSData, which you can store among the preferences.
You can only put basic foundation types into a property list. NSUserDefaults writes preferences out as a property list. See here for property list allowed types. In a nutshell, it is numbers, strings, data, dates, and arrays and dictionaries of those. Dictionaries must have string keys.
NSUserDefaults always returns immutable objects, so you can't just cast them to mutable. Do [prefs objectForKey:#"my_adventure_book_albums"] mutableCopy] (and remember to release it when finished).