Reputation: 5232
I have a app in which I need to copy my database file to document directory. I know how to do that and it is working good. Here is the code for it
// Get Required Path
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
// Check if DB file already Exist. If YES than return.
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
// If DB file is not exist try to write file. This will execute first time only.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// Add Skip Backup attribute here.
This works fine but due to some reason sometimes it generates error. Now the problem is When I try to trace this problem it doesn't occur.
I don't know why but success = [fileManager fileExistsAtPath:writableDBPath];
is returning NO. Than it attempt to write new file but writing new file gets fail also. Its very hard to trace the error
as it is not reproducing in my testing.
Can anyboday tell me the possible errors due to this happening and provide solution.
Thanks
Upvotes: 2
Views: 261
Reputation:
Try with Following code
BOOL copySucceeded = NO;
// Get our document path.
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
// Get the full path to our file.
NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
// Get a file manager
NSFileManager *fileManager = [NSFileManager defaultManager];
// Does the database already exist? (If not, copy it from our bundle)
if(![fileManager fileExistsAtPath:filePath]) {
// Get the bundle location
NSString *bundleDBPath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
// Copy the DB to our document directory.
copySucceeded = [fileManager copyItemAtPath:bundleDBPath
toPath:filePath
error:nil];
if(!copySucceeded) {
//not Copy
}
else {
// Success
}
}
else {
// Nothing
}
Upvotes: 1