I just started with iPhone development. In one of the example where I had to display some data stored in sqlite db in a table view in a tabbar controller, I had to move a sqlite file from application bundle to the documents folder.
I used the application template - iOS > Application > Window-based application for iPhone (Used core data for storage)
In the template generated by XCode (base sdk set to latest iOS = 4.2), the following code was there...
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
In trying to get a path to documents folder, I used the method given above like this...
NSString *documentDirectory = [self applicationDocumentsDirectory];
This gave a warning - warning: incompatible Objective-C types initializing 'struct NSURL *', expected 'struct NSString *'
So I changed the code to following...
// Added the message absoluteString over here
NSString *documentDirectory = [[self applicationDocumentsDirectory] absoluteString];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
And BOOM!!! It gave the error that - 'Failed to create writable database file with message 'The operation couldn’t be completed. No such file or directory'.'
How should I find the path to documents directory since the method applicationDocumentsDirectory
generated by XCode template does not work for me.
Also, can somebody throw some light on the purpose of applicationDocumentsDirectory
method given above.
Thanks
heres a simple way to do it:
NSFileManager *fmngr = [[NSFileManager alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mydb.sqlite" ofType:nil];
NSError *error;
if(![fmngr copyItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/Documents/mydb.sqlite", NSHomeDirectory()] error:&error]) {
// handle the error
NSLog(@"Error creating the database: %@", [error description]);
}
[fmngr release];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With