Jul 05

With this post I will show how to copy a file added to our project to the documents folder of our application. The idea is to be able to initialize in a fast and easy way the database, some configuration files or any similar file that we must save in the documents folder because it will be change by the user during runtime. That way we don’t have to create them from the code.

First, we need to add the file to our project, add it to the “Resources” folder of your project so it is accessible from the code of your application.

Once we have the file in the project, we can add the code to copy the file to the documents folder, add the next code to your AppDelegate, you can create a new method for initialization purpose or add it directly to the AppDelegate init.

// Copy init.sqlite from resources to the Documents folder in bundle
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"data.sqlite"];
if(![[NSFileManager defaultManager] fileExistsAtPath:storePath])
{
	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"init" ofType:@"sqlite"];
	NSData *myData = [NSData dataWithContentsOfFile:filePath];
	if (![myData writeToFile:storePath atomically:YES]) {
		NSLog(@"ERROR writting the starting database");
	}
}

In the code we use a file, init.sqlite, as an initial database for our application and we save the same file under the name data.sqlite in the documents folder of our application. Notice that we use an if to check if that file already exists, that way this code will only be executed the first time we launch our application, this is so we don’t delete any new data the user may have introduced. If during your testing you want to get the initial database again, delete the application from your iPhone or from the iPhone Simulator.

The method applicationDocumentsDirectory is the following function, returning the path to the documents folder.

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
VN:F [1.9.8_1114]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.8_1114]
Rating: +1 (from 1 vote)
How to copy a file from our project to the documents folder of our application, 5.0 out of 5 based on 1 rating

Leave a Reply

You must be logged in to post a comment.

preload preload preload