How to retrive data from document directory when application start? - iphone

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...

Related

Unable to retrieve NSMutableArray from NSUserDefaults

I have an issue persisting data in local storage for an NSMutableArray containing a list of NSStrings.
I have a save method and a get method both appear to work when the app is running. However, once I close the app and restart the items in the array are gone.
NSMutableArray*ImageTags;
Get Data
-(NSMutableArray*)GetDataNSMutableArray:(NSString*)ItemName
{
NSMutableArray *GetData = [[NSMutableArray alloc] init];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:ItemName];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
GetData = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
GetData = [[NSMutableArray alloc] init];
}
return GetData;
}
Save Data
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
}
How items are added
[ImageTags addObject:Control.titleLabel.text]
How array is saved
[super SaveDataNSMutableArray:CVC_ImageURL:ImageTags];
How array is retrieved
ImageTags = [super GetDataNSMutableArray:CVC_ImageURL];
NSUserDefaults always return immutable instances.
Unrelated:
(Conventions says that methodNames should always begin with a small letter).
[[NSUserDefaults standardUserDefaults] synchronize]
To dump all the contents from NSUserDefaults onto persistent store
Your can not store mutable array to user defaults. Store the immutable copy and retrieve that and convert to mutable ones to access during the next launch.
You can do synchronization while saving:
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
[[NSUserDefaults standardUserDefaults] synchronize] //add this code of a line.
}

NSUserDefaults display date and data in the tableView

In the FirstViewController of my survey app I have NSMutableArray that contains data (strings). I've also created date varibale. Here's code
NSDateFormatter *dateformater=[[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"EEEE,dd MMMM yyyy HH:mm a"];
NSDate *today=[NSDate date];
NSString *currentDate=[dateformater stringFromDate:today];
Now I want with the help of NSUserDefaults save data from the array and also save date variable when the survey has been taken and display it in the SecondViewController's tableview (first user can see date of the survey and then by tapping the date - data from array).
I know how NSUSerDefaults work but I don't know how to put array by date variable to be shown in the SecondViewController. Can anyone help me on that?
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *arrDate;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"arrDate"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
arrDate = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
arrDate = [[NSMutableArray alloc] init];
} else {
arrDate = [[NSMutableArray alloc] init];
}
[arrDate retain];
after that when you want to insert,update or delete Data from this UserDefaults Use Bellow Code...
for Delete record from array
[appDelegate.arrDate removeObjectAtIndex:Index];/// give the integer value instead of Index
and this is for add record in array..
[appDelegate.arrDate addObject:currentDate];///add value or add date here
after in final save this modification in array just archive like bellow..
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.arrDate];
[appDelegate.userDefaults setObject:data forKey:#"arrDate"];
[appDelegate.userDefaults synchronize];
Create a NSDictionary with the date and data object:
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",currentDate], #"date", #"yourData", #"data", nil];
Then put it in the NSUserDefault using:
[NSUserDefaults standardUserDefaults] setObject:yourDictionary forKey:#"item1"];
This will store a single data to NSUserDefault.
You can retrieve the object by using:
NSDictionary * dictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"item1"];
Now you will get the date using [dictionary objectForKey:#"date"]; and data using : [dictionary objectForKey:#"data"];

NSUserdefaults for multiuser

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....

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

Saving NSMutableArray to plist? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
iOS: store two NSMutableArray in a .plist file
In the app I'm working on I have a bunch of "Registration" objects that contain some strings,dates and integers.
All of these objects are stored in a NSMutableArray when they're created, and I now want to save this array in someway, so that when the user closes the app etc., the content can be stored and restored when app opens again.
I've read that plist is probably the best way to do so, but I can't seem to find any examples, posts etc. that show how to do it?
So basicly: How to I save my NSMutableArray to a plist file when app closes, and how to restore it again?
NSMutableArray has a method for doing this, if you know exactly where to save it to:
//Writing to file
if(![array writeToFile:path atomically:NO]) {
NSLog(#"Array wasn't saved properly");
};
//Reading from File
NSArray *array;
array = [NSArray arrayWithContentsOfFile:path];
if(!array) {
array = [[NSMutableArray alloc] init];
} else {
array = [[NSMutableArray alloc] initWithArray:array];
};
Or you can use NSUserDefaults:
//Saving it
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"My Key"];
//Loading it
NSArray *array;
array = [[NSUserDefaults standardUserDefaults] objectForKey:#"My Key"];
if(!array) {
array = [[NSMutableArray alloc] init];
} else {
array = [[NSMutableArray alloc] initWithArray:array];
};