Copy file to App Document folder automatically - objective-c

I want to copy set of files from project resource folder to the app document folder automatically at the time of app first launch. Can I do this. Do I need to do it through the code.

BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Data.txt"];
success = [fileManager fileExistsAtPath:filePath];
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"txt"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
}
In application did finish launching with options

Related

how to add a file to my project programmatically

I created a WinDef.plist file in the Application Support folder which contains default values.
I would like to add this file to my project without doing it manually.
Any idea how I could do it?
Ronald
Try following methods in your application didfinishlaunching method
-(void) checkAndCreateFile
{
//-------------------------------------------
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:cFilePath];
//-------------------------------------------
//File already there
if(success)
{
return;
}
//-------------------------------------------
//create file
NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:cfileName];
[fileManager copyItemAtPath:filePathFromApp toPath:cfilePath error:nil];
}
//------------------------------------------------------------------------
// Method : copyFile
// Method to create file
//------------------------------------------------------------------------
-(void) copyFile
{
cfileName = #"WinDef.plist";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentsPaths objectAtIndex:0];
cfilePath = [documentDir stringByAppendingPathComponent:cfileName];
[self checkAndCreateFile];
}
This will save WinDef.plist file in your application document folder if you want
And if you want to access that file values then you can retrieve it by using following code
NSString *path = [[NSBundle mainBundle] pathForResource: #"WinDef" ofType: #"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile: path];
id obj1 = [dictionary objectForKey: #"YourKey"];
This will give you that key value in dictionary

Xcode - Save sqlite3 database in Library folder

I'm developing a app that use a Sqlite3 database. For now the db is inside app package, but I know that I'll have problems to update the data when I test in real world, with a real iPhone.
1 - How can I copy, at bundle phase, my project database to Library folder?
2 - How can I access this copied database? For now my code is:
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"myDatabase.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
What I'll have to change?
3 - How can I preserve this database (with the user's data) if I update the app?
Thanks in advance! ;)
You have to copy the database from the Resources folder to Documents folder
sqlite3 *database;
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Lists.db"];
success = [fileManager fileExistsAtPath:writableDBPath];
// The writable database does not exist, so copy the default to the appropriate location.
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Lists.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
TFLog(#"Failed moving database... %#",[error localizedDescription]);
return;
}
}
When you update your app database in your Documents folder will be their you just need to check the condition
success = [fileManager fileExistsAtPath:writableDBPath];
if it does not exits new database will be copied their.
Just keep in mind database structure is same as before.

Objective-C / Can't access (read) file in "Resources" folder

This is probably a very easy problem to solve but i have not succeeded. I have copied the file "questions_famquiz_easy_110326.txt" to the resources folder and now want to access (read) it and NSLog it to see that i am able to read it.
The code below is from one of the tests i have done based on examples that i have found on the web.
I am trying to access a txt-file in the Resources folder and fail to do so. I have searched for a solution, tested a lot, but not succeeded.
I am testing with the following code:
NSLog(#"\n \n >>>>>>viewDidLoad<<<<<<<<<");
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
if(![fileManager fileExistsAtPath:filePath])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/questions_famquiz_easy_110326.txt"]];
[data writeToFile:filePath atomically:YES];
}
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myString: %#", myString);
NSLog(#"\n \n>>>>>>DONE WITH viewDidLoad<<<<<<<<<");
exit(0); //====EXIT JUST FOR THE TEST====<<<
The above code is located in the first viewController that is started.
The output i get is:
>>>>>>viewDidLoad<<<<<<<<<
2011-04-24 21:53:47.825 FamQuiz_R0_1[542:307] myString: (null)
2011-04-24 21:53:51.044 FamQuiz_R0_1[542:307]
>>>>>>DONE WITH viewDidLoad<<<<<<<<<
Could someone nice help me to solve this?
update:
Here is the filePath:
2011-04-24 22:38:08.562 FamQuiz_R0_1[637:307] filePath: /var/mobile/Applications/7F5FDB03-0D22-46BC-91BC-4D268EB4BBEB/FamQuiz_R0_1.app/questions_famquiz_easy_110326.txt
Here is where i have placed the file:
PROBLEM SOLVED:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
When i used the above it did not work, when i used the below it worked and printed out the text.
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
You're not reading from the resources folder. You're trying to read from the document directory. So getting back nil makes sense since the file doesn't exist there.
Change:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
to:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"questions_famquiz_easy_110326" ofType:#"txt"];
and it should work for you.

SQLite Step Failed: attempt to write a readonly database , using wrapper

I keep getting an error "SQLite Step Failed: attempt to write a readonly database" when using this code to copy a database:
-(void)createEditableCopyOfDatabaseIfNeeded
{
// Testing for existence
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath =
[documentsDirectory stringByAppendingPathComponent:#"Money.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to
// the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"Money.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with Message : '%#'.",
[error localizedDescription]);
}
}
I am using the above code in AppDelegate
and this:
NSString *writableDBPath =
[[NSBundle mainBundle] pathForResource:#"Money"
ofType:#"sqlite"];
In ViewController.m
I am using http://th30z.netsons.org/2008/11/objective-c-sqlite-wrapper/ what am I doing wrong?
This is happening again and again... It was working fine before but again the problem started.
The problem is that you cannot write anything to your bundle. To be able to change your database you need to copy it to application's documents or caches folder and work with that copy.

Copying plist file to custom folder in ApplicationSupport (Objective-C)

I have this piece of code, which copies a plist file to the ApplicationSupport directory in the users folder.
NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kAutonumberPlist];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:kAutonumberPlist];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dataPath]) {
[fileManager copyItemAtPath:resourcePath toPath:dataPath error:nil];
}
How ca I change it so that instead of copying the file into ~User/Library/ApplicationSupport, it will copy it into ~User/Library/ApplicationSupport/AnotherFolder. The "AnotherFolder" already exists by the way.
Thank you!
You are already using stringByAppendingPathComponent - you could just use it again.
For example:
NSString *dataPath = [[[paths objectAtIndex:0]
stringByAppendingPathComponent: #"AnotherFolder"]
stringByAppendingPathComponent: kAutonumberPlist];