Can't save and load plist file - ios

When i tried to create plist file('Checklist.plist') using following methods i can't see the file in the directory.
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory; }
- (NSString *)dataFilePath {
return [[self documentsDirectory] stringByAppendingPathComponent:#"Checklists.plist"];
}
Why i can't see the file on the directory? How can i solve this problem?

Did you save something in the file?
NSString *test = #"test";
[test writeToFile:[self dataFilePath] atomically:YES];
If you run this in a simulator, you can NSlog this file path, and than open finder, press cmd + shift + g paste the file path, don't include Checklist.plist, just documents file path, you will see the file you just create named Checklist.plist.
This is all my code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *testArray = [NSArray arrayWithObjects:#"test", nil];
[testArray writeToFile:[self dataFilePath] atomically:YES];
}
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
}
- (NSString *)dataFilePath {
return [[self documentsDirectory] stringByAppendingPathComponent:#"Checklists.plist"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

The file isn't created when -dataFilePath is called.
To write a plain string in your file, use:
NSError *e = nil;
[#"blabla" writeToFile:[self dataFilePath] atomically:YES encoding:NSUTF8StringEncoding error:&e];
NSError *e1 = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:[self dataFilePath] encoding:NSUTF8StringEncoding error:&e1];
Both errors should be nil and fileContents should contain the original string.

Related

how to copy file from main bundle to Document Folder

I want to check one file in Document folder.I want if this file not exist in document folder copy it from main bundle to document folder. I write this code and this file to be copy but my problem here.....!!!! my file is .sqlite file (Database file) and when copy to document folder hasn't data in self!!!! why??? while the this file when is in main bundle has data in self.
this is my code but I don't know why not work!!!!
#define DataName #"mydatabase.sqlite"
- (void)viewDidLoad
{
[self CopyDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (NSString*)DatabasePath
{
NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDir = [Paths objectAtIndex:0];
//NSLog(#"%#",DocumentDir);
return [DocumentDir stringByAppendingPathComponent:DataName];
}
- (void)CopyDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:[self DatabasePath]];
NSString *FileDB = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DataName];
if (success)
{
NSLog(#"File Exist");
return;
}
else
{
[fileManager copyItemAtPath:FileDB toPath:[self DatabasePath] error:nil];
}
}
I don't think your documents folder is updating because an older version of that db exists. You can purge your documents directory with the following method, and add it to the top of your viewDidLoad:
- (void)viewDidLoad
{
[self purgeDocumentsDirectory];
[self CopyDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)purgeDocumentsDirectory
{
NSLog(#"Purging Documents Directory...");
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}
}
This is my solution
-(void) copytoDocument {
NSString *openFile ;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pgnPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.text", #"100_Greatest_games"]];
if ([fileManager fileExistsAtPath:pgnPath] == NO)
{
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"100_Greatest_games" ofType:#"text"];
[fileManager copyItemAtPath:resourcePath toPath:pgnPath error:&error];
if (error) {
NSLog(#"Error on copying file: %#\nfrom path: %#\ntoPath: %#", error, resourcePath, pgnPath);
}
}
}

iOS QLPreviewController show pdf saved to file system

I have QLPreviewController working if I show a PDF file system from my bundle on the project,
like this example
but If I want to show a PDF from the file system, it doesnt show it, how can I call a pdf file that I have just downloaded in my file system?
The code:
- (void)initPDFviewer
{
QLPreviewController *previewController=[[QLPreviewController alloc]init];
previewController.delegate=self;
previewController.dataSource=self;
[self presentModalViewController:previewController animated:YES];
[previewController.navigationItem setRightBarButtonItem:nil];
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
return 1;
}
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
//return 0;
//return url!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"paths :: %#", paths);
return 0;
}
So my problem is how to get the pdf [only pdf in the documents directory], how do i get this pdf?
thanks
thanks!
Change your init method to below.
-(id)init
{
if (self = [super init])
{
// arrayOfDocuments = [[NSArray alloc] initWithObjects:
// #"iOSDevTips.png", #"Remodel.xls", #"Core J2ME Technology.pdf", nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docPath = [paths lastObject];
NSArray *docArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:nil];
arrayOfDocuments = [[NSArray alloc] initWithArray:docArray];
}
return self;
}
Add this new method
-(NSString*)documentDirectoryPathForResource:(NSString*)aFileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:aFileName];
return fullPath;
}
And replace your method with my method
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
// Break the path into it's components (filename and extension)
NSString *path = [self documentDirectoryPathForResource:arrayOfDocuments[index]];
return [NSURL fileURLWithPath:path];
}
Code is self explanatory. Just create the array of all the documents that are in your document directory. And after that use that array to create the path and provide URL of that path to QLPreviewController
NSURL *fileURL = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *wordFilePath = [documentsDirectory stringByAppendingPathComponent:#"sample.doc"];
fileURL = [NSURL fileURLWithPath:wordFilePath];
return fileURL;

Save new plist file with filename equal to the value from a string variable

I am creating an iPhone application that will write the application data to a plist file, in which one of the text fields contains ProjName.text.
How can I save a plist file with the name of ProjName.text.plist.
For example, if the value of ProjName is "Servers" how do I save out of my array to a "Servers.plist" file?
This should work:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destination = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist", textfield.text];
[fileData writeToFile:destination atomically:YES];
[self savePlist:#"Servers" fromArray:yourArray]; //or
// [self savePlist:textField.text fromArray:yourArray];
#pragma mark - plist
- (NSString *) getFilePathForPlist:(NSString *) plistName {
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
}
-(void) savePlist:(NSString *)plistName fromArray:(NSMutableArray *)array {
[array writeToFile:[self getFilePathForPlist:plistName] atomically:YES];
}

Saving a state of button even after its parent view is dismissed in iOS

How to save the background color state of a button after its parent view is removed. So dat the next time i click on the button after the parent view is again loaded I can change the initial color of the button.
You can go for PList.
Try this:-
In AppDelegate.h
+(NSString *)getValueFromPlist:(NSString *)key filename:(NSString *)filename;
+(NSString *)dataFilePath:(NSString *)filename;
In AppDelegate.m
+(NSString *)getValueFromPlist:(NSString *)key filename:(NSString *)filename
{
NSString *path = [AppDelegate dataFilePath:filename];
//NSLog(#"\npath - %#\n", path);
NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:path];
//NSLog(#"\nparsing- %#", dict);
return [dict valueForKey:key];
}
+ (NSString *)dataFilePath:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
return [docDirectory stringByAppendingPathComponent:filename];
}
In yourViewController.m, use this code to save value in plist :-
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:#"Your Value to be saved" forKey:#"value"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"nameOfPlist.plist"];
[dict writeToFile:path atomically:YES];
Next time, get the value from plist and use it your code :-
NSString *strValue = [AppDelegate getValueFromPlist:#"value" filename:#"nameOfPlist.plist"];

getting data from plist to NSMutableArray and writing the NSMutableArray to same plist iPhone

Using this code I am trying to get the data from Templates.plist file but I am getting null value in array.
//from plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Templates" ofType:#"plist"];
NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog(#"arrayArray:::: %#", arry);
This is my plist file:
Also I want to know how can I add more strings to this plist file and delete a string from this plist.
First off you cannot write to anything in you mainBundle. For you to write to you plist you need to copy it to the documents directory. This is done like so:
- (void)createEditableCopyOfIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"Template.plist"];
success = [fileManager fileExistsAtPath:writablePath];
if (success)
return;
// The writable file does not exist, so copy from the bundle to the appropriate location.
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Template.plist"];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable file with message '%#'.", [error localizedDescription]);
}
So calling this function will check if the file exists in the documents directory. If it doesn't it copies the file to the documents directory. If the file exists it just returns. Next you just need to access the file to be able to read and write to it. To access you just need the path to the documents directory and to add your file name as a path component.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"Template.plist"];
To get the data from the plist:
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
To write the file back to the documents directory.
[array writeToFile:filePath atomically: YES];
-(NSMutableArray *)start1
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Templates.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
plistArr = [NSMutableArray arrayWithContentsOfFile: plistPath];
}
else {
plistArr = [[NSMutableArray alloc] init];
}
return plistArr;
}
- (void)createNewRecordWithName:(NSMutableDictionary *)dict
{
plistArr=[self start1];
[plistArr addObject: dict];
//[dict release];
[self writeProductsToFile:plistArr];
}
- (void)writeProductsToFile:(NSMutableArray *)array1 {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Template.plist"];
[array1 writeToFile:plistPath atomically:YES];
}
To get a plist into a mutable array, use this class method:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
Then, add/delete strings from the array. To save the array back to a plist, use:
[array writeToFile:path atomically:YES];

Resources