PList Chicken/Egg Scenario - iphone

I want to read/write to cache.plist
If I want to read an existing premade plist file stored in the resources folder I can go:
path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathWithComponent#"cache.plist"];
NSMutableDictionary *root = ...
But then I wish to read it from the iPhone.
Can't, the Resources folder is only readable.
So I need to use:
NSDocumentDirectory, NSUserDomain,YES
So how can I have my plist file preinstalled to the Document Directory location?
Thus meaning I don't have to mess around with untidy code copying the plist file over at startup. (Unless that's the only way).

I know this isn't really what you're after, but as far as I know the only way to get the document into the Documents folder IS to actually copy it there...but only on the first startup. I'm going something similar for a sqlite database. Code is below, it works but please note it could do with a little bit of cleaning up:
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"WordsDatabase.sqlite3"];
createdDatabaseOk = [fileManager fileExistsAtPath:writableDBPath];
if (createdDatabaseOk) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"WordsDatabase.sqlite3"];
createdDatabaseOk = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
}
Just call in your AppDelegate - not too messy really?

Easy. Look first to see if it's in the documents directory. If it's not, find it inside your app's Resources folder ([[NSBundle mainBundle] pathForResource...]), then copy it into the documents directory using [[NSFileManager defaultManager] copyItemAtPath:...]. Then use the fresh copy in the documents directory with impunity.

The final product
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"Cache.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *giveCachePath = [documentsDirectory stringByAppendingPathComponent:#"Cache.plist"];
BOOL fileExists = [fileManager fileExistsAtPath:giveCachePath];
if (fileExists) {
NSLog(#"file Exists");
}
else {
NSLog(#"Copying the file over");
fileExists = [fileManager copyItemAtPath:finalPath toPath:giveCachePath error:&error];
}
NSLog(#"Confirming Copy:");
BOOL filecopied = [fileManager fileExistsAtPath:giveCachePath];
if (filecopied) {
NSLog(#"Give Cache Plist File ready.");
}
else {
NSLog(#"Cache plist not working.");
}

Related

how to create a directory in iphone settings in objective c

I am new programmer in objective c. I want to create "Download" directory inside the i phone(path : setting (i phone setting directory))I want to know is it possible?. I am using i phone simulator to test the program.
Another question is, How can I access created directory in i phone simulator. Below contains code I tried to create folder in i phone. But I can not access that directory by using i phone simulator. what the wrong of this code?
NSString *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Test"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
you can create Directory in to Document Directory as sub Folder like this way:-
-(IBAction)CreatDirInDocDir
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dir = [NSString stringWithFormat:#"%#",DirName];
NSString *path = [documentsDirectory stringByAppendingPathComponent:dir];
NSError *error;
if ([filemgr fileExistsAtPath:path ] == YES){
}
else
{
NSLog (#"File not found");
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
}
}
when ever you create directory in to Document directory folder then you can get all list of Created Custom directory like this way:-
//Get all Directory
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSMutableArray *directoryList=[[NSMutableArray alloc]init];
for ( NSString *direPath in filePathsArray )
{
NSString *path = [documentsDirectory stringByAppendingPathComponent:direPath];
BOOL isDir = NO;
[fileMan fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
NSLog(#"log path ==%#",fullPath);
[directoryList addObject:fullPath];
}
}
NSLog(#"list path ==%#",directoryList);
Now you have array of all directory you can get any directory with index :)
Hope its helps you
All The method posted here are correct and there are tons of answers about them, but I'd like to warn you about a concept. Since The introduction of iCloud, Apple started to reject applications that saves a lot of data in document directory, when they are used by means of caches or they could be downloaded again later. The problem here is that you can backup your ios devices on the cloud and document directory is one of the backupped. Can you image yourself backupping one GB on application on the cloud? That's the explanation about apple rejects. To avoid that temp/redownloadable/cached data should be saved in cache directory. This useful dir is freed when the device is running out of space on "disk", like when you try to install a new app and you don't have enough space. So this is ok if your data can be downloaded again and are not indispensable. the other way around is to keep data in the document directory but telling the system to do not backup them, this is possible adding a special flag to the doc subdirectory where you saved the file, here is how link , pay attention that this methods is only available from 5.0.1 so you need to check its existence if you target lower ioses. In this case the system will not free your data and not backup them this is safe for apple guidelines. hope this helps
For creating directory you can use:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Test"];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
{
NSLog(#"Couldn't create directory error: %#", error);
}
For getting the files inside that directory you can use:
NSArray *datArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:&error];
if(error)
{
NSLog(#"Could not get list from directory, error = %#",error);
}
Here all file names will be in the datArray.
No need append '/' . Just Use
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Test"];
Try This
NSArray *dirPath;
NSString *docsDir;
NSFileManager *filemgr = [NSFileManager defaultManager];
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
if ([filemgr changeCurrentDirectoryPath: docsDir] == NO)
{
NSLog(#"Error");
}else {
NSString *currentPath = [filemgr currentDirectoryPath];
NSLog(#"%#",currentPath);
}
NSString *dataDirectory = [docsDir stringByAppendingPathComponent:#"Test"];
if ([filemgr fileExistsAtPath:dataDirectory]){
NSLog(#"dir Exist");
}else{
NSLog(#"Creating Dir");
[filemgr createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
Anyone want to show your created directory in i phone simulator follow bellow steps :
Go to finder
Click Command +Shift + g
Type ~/Library then click Go
Open Application Support --> i phone simulator
Then you can find your created applications and directories..

Copy folder from Resource to Document in iphone sdk

i have one subfolder in Resources with name SketchImages which contains 300 PNG images, what i need to do is on the startup of my app copy this folder in document folder of iphone sdk, i am trying the following code with no luck
BOOL success;
NSFileManager *fileManager = [[NSFileManager defaultManager] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory
stringByAppendingPathComponent:#"SketchImages"];
success = [fileManager fileExistsAtPath:documentDBFolderPath];
if (success)
{
return;
}else
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"DB"];
//[fileManager createDirectoryAtPath: documentDBFolderPath attributes:nil];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath
error:&error];
}
any help will be highly appriciated
You use the wrong subfolder name:
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"SketchImages"];

objective c,checking file exist at path

I have created a screen using Objective-C in an iPhone project. In that, there are 2 buttons (say A and B). On the click of button A, one xml file will be created in a folder (say INBOX).
My problem is, I need to create the file only if it does not exist at folder INBOX.
How can I do this? Can any one tell me the syntax?
Can you Please Check NSFileManager.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathForFile;
if ([fileManager fileExistsAtPath:pathForFile]){
}
try this:
- (BOOL)checkAndCopy {
NSError **error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourFile.xml"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
// this copy an existing xml (empty?) file from main bundle:
// try else to create a new file
NSString *bundle = [[ NSBundle mainBundle] pathForResource:#"yourFile" ofType:#"xml"];
[fileManager copyItemAtPath:bundle toPath:path error:error];
return YES;
}
return NO;
}
There have been similar questions on SO before:
This answer is probably most appropriate for you
Link to the NSFileManagerAPI

Creating a plist file only on first runnable in the device's documents directory

I current have everything setup to read from the documents directory and write to it , but Cannot do it because the file doesnt exist yet.
How is a file created within the code?
If you already have a template version of the document in your application's bundle then you should be able to write it to the application's document directory using something similar to the following. I haven't tested this code so I've probably got a few things wrong but that's the general idea.
- (void) applicationDidFinishLaunching {
NSArray* directories = NSSearchPathsForDirectoriesInDomain(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [directories objectAtIndex: 0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: #"Something.plist"];
if (![[NSFileManager sharedInstance] fileExistsAtPath: path]) {
NSString* infoTemplatePath = [[NSBundle mainBundle] pathForResource: #"Something" ofType: #"plist"];
NSDictionary* info = [NSDictionary dictionaryWithContentsOfFile: infoTemplatePath];
[info writeToFile: path];
}
}
Use NSFileManger's fileExistsAtPath: to see if the file exist. If not create it before going on to the code that requires the file.
This one works better for me:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:#"*.db"];
if (![fileManager fileExistsAtPath:documentDBFolderPath])
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"*.db"];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
}

Adding file to Documents Directory (or elsewhere)?

I want to initialize my app with a small sqlite3 DB. I tried to put it in the Documents directory, but sometimes it copies it with zero size and sometimes it doesnot copy it at at all.
How sholud I initialize my app with a DB full of info?
Thankyou
How do you copy it with your application?
If you ship your application with DB inside app bundle (as a resource) you should copy it to the documents folder from resources if it is absent and work with it there:
NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];
BOOL exists = [fileManager fileExistsAtPath:databasePath];
if (exists) {
return;
}
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
Thank you Vladimir,
This was helpful. I made a few changes and here is the final result that works great:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = #"personalLMS.s3db";
NSFileManager *fileManager = [[NSFileManager defaultManager] autorelease];
NSString * databasePathFromApp = [[NSBundle mainBundle] pathForResource:#"personalLMS" ofType:#"s3db"];
[fileManager copyItemAtPath:databasePathFromApp toPath:[documentsDirectory stringByAppendingPathComponent:databasePath] error:nil];