Writing to a .plist file - arrays

I have a .plist with 2 key values in it. It is of type Dictionary. I am trying to write value to one of the key values. What's wrong with the code below? I also tried using type "Array". That option also does not work. How can I get it to work using Dictionary & also Array? Anyone has working code example? Thanks. I would appreciate any help.
NSString *filePath = #"myprefs.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:#"test#test.com" forKey:#"Email"];
[plistDict writeToFile:filePath atomically: YES];

You did not initialize the path properly.
If "myprefs.plist" is inside the resources folder of your project then initialize like this:
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"myprefs" ofType:#"plist"];
If its somewhere else in your computer, specify the whole path

Related

UIFIleSharing populating UIPickerView

I'm new to the site and probably even newer to app development, however i'm learning slowly.. lol
So i hit my first big snag, I've researched all over on the web and can't find what I'm looking for, so here we go.
I'm creating an app that calls upon some user inputted files that can and do change on occasion. I've added the UIFileSharing option for this so users can upload files via iTunes.
There are 3 different types of files that will need to be used, a .opt, a .pkg, and a .txt.
Is there some way i can take the files from the directory, read them, and based off the file extension pull them and use them in a UIPickerView wheel? I'm really new at this so please forgive me when i ask you to be specific.
My assumption is to do this in a few steps, first read the files and sort them and place them in an array based on the extension, then use said array to populate the picker, and also to get the count for number of rows etc..
I guess the second two parts are pretty simple to figure out, just setting up a picker to use an array, i just need to know if its possible to build that array based on the user loaded files.
thanks in advance,
Chuck
You'll need to use the UIDocumentInteractionController class.
Simple Example
UIDocumentInteractionController * controller;
NSURL *fileURL=[NSURL fileURLWithPath:[self getFilePath]]
controller = [ UIDocumentInteractionController interactionControllerWithURL: fileURL ];
// How to get File From the Document Directory
-(NSString *)getFilePath{
NSString *documentPath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
return [documentPath stringByAppendingPathComponent:#"Your file name"]
}
I solved it guys, thanks for all the help.. Code is below, for anyone interested. Don't forget to define your arrays!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *bundleDirectory = [fileManager contentsOfDirectoryAtPath:documentsPath error:nil];
NSPredicate *Option = [NSPredicate predicateWithFormat:#"self ENDSWITH '.opt'"];
_OptionArray = [bundleDirectory filteredArrayUsingPredicate:Option];
_OptionPickerData = [_OptionArray copy];

nsfilemanager createFileAtPath results in NSFileCreationDate being null

I am creating an image file from a json object and the file creation is successful and the image is indeed created and can be displayed. I want a process that will check if the file is still in cache or a tmp directory before downloading the image. If the image is indeed there then I want to check the creation date and modification date attributes of the file to see if I need to download a new version of the image to keep it up to date. This is where the problem comes in.
The creation and modification date attributes are null. I've even attempted to manually set the attributes and it didn't change anything.
Here's the code I use to create the file:
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:#"tmp/%#",theFileName]];
BOOL filecreationSuccess =[fileManager createFileAtPath:fileName contents:myData attributes:nil];
if(filecreationSuccess == NO){
NSLog(#"Failed to create the file");
}
I have even tried adding the Code and the attributes on the file are still null:
NSDate *now = [NSDate date];
NSDictionary *createDateAttr = [NSDictionary dictionaryWithObjectsAndKeys: now, NSFileCreationDate,nil];
NSDictionary *modDateAttr = [NSDictionary dictionaryWithObjectsAndKeys: now, NSFileModificationDate, nil];
[fileManager setAttributes:modDateAttr ofItemAtPath:fileName error:&err];
[fileManager setAttributes:createDateAttr ofItemAtPath:fileName error:&err];
I am unsure of what to do next. Any help would be greatly appreciated, Thank you.
I have found my problem. It wasn't that the modification and creation dates weren't being set, but that I was not getting the correct set of properties for the file. It ended up being that the code I was using was getting the properties for the path that the file was in, not the file itself.

Update existing plist on iOS5 simulator

I am trying to update an existing plist on iOS5 simulator but it fails miserably.
It finds the plist and retrieves existing information and updates the array but it does not write to file.
Any one would have any ideas?
NSString *path = [[NSBundle mainBundle] pathForResource:#"content_iPhone" ofType:#"plist"];
NSMutableArray *plist = [[NSMutableArray arrayWithContentsOfFile:path] mutableCopy];
// For testing purpose, get an object from the Array and add the object to array
newObject = [plist objectAtIndex:1];
[plist addObject:newObject];
[plist writeToFile:path atomically:YES];
You can't write to a file inside your app bundle, you can only read from it.
You could write the file to the user's Documents directory instead: look at
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
This returns an array, the first object of which will be the path to the user's Documents directory for your app. You could copy the file there the first time your app is run, and update it at that location in the future.

How to write an NSArray of UIImage objects to file?

I have been attempting to use NSMutableArray's writeToFile:atomically:
But it has been pointed out to me that this approach is wrong: i.e. iPhone / Objective-C: NSMutableArray writeToFile won't write to file. Always returns NO
It looks like I'm going to have to read the guide on archiving that is referred to in one of the answers in the above link.
Would anyone care to share (or point me towards) some code that helps me accomplish this task?
The method, you've mentioned recursively validates that all the contained objects are property list objects before writing out the file.
Try this:
for (UIImage *image in arrayWithImages) {
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#", #"nameOfTheImage.png"]];
UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
}
Maybe you can use [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES]; to write image as jpeg.

Restore file with data cocoa?

How can I restore a file with certain data. If a user enters a file in which he wants the data to be restored with, and that file is not there, it should be created with that data. This is all part of an encryption tool. So say I, the user, selects a file, and encrypts it. So I have my encrypted data. But now I need to move this encrypted data to a file, so that the user can take the file that contains the encrypted data, to decrypt, so that he gets his original file provided he entered the correct key.
Hopefully that was clear enough. All help is greatly appreciated.
Use NSFileManager to get (and possiby create) the file path for the data, then writeToFile: methods. Something like this:
- (void) saveCriteriaToFile: (NSArray *) criteria
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDir = [[paths objectAtIndex:0] stringByAppendingPathComponent: #"StokerX"];
NSString *saveFilePath = [supportDir stringByAppendingPathComponent: kSavedNotificationsFile];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: saveFilePath] == NO)
{
[fileManager createDirectoryAtPath: supportDir withIntermediateDirectories:YES attributes:nil error:nil];
}
[criteria writeToFile:saveFilePath atomically:YES];
}
This one is writing an NSArray object to a pilist, but you do it almost the same with an NSData object.
I fixed my problem by using NSHomeDirectory instead of hardcoding the path. Thanks though for the help.

Resources