Reputation: 31283
I'm doing a small database driven app. I have my SQLite db file under Supporting Files in xcode. At first I was trying to write data to it when it was in the mainbundle but couldn't. After searching, I came across this answer and I changed my code to the following.
- (void)viewDidLoad
{
[super viewDidLoad];
BOOL success;
NSFileManager *filemngr = [[NSFileManager alloc] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDbPath = [documentDirectory stringByAppendingPathComponent:@"contacts.sqlite"];
success = [filemngr fileExistsAtPath:writableDbPath];
if(!success)
{
[status setText:@"Error occurred!"];
}
NSString *defaultDbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"contacts.sqlite"];
success = [filemngr copyItemAtPath:defaultDbPath toPath:writableDbPath error:&error];
if (!success)
{
[status setText:[error localizedDescription]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
I get the following error in the final if block when I'm trying to copy the file to the writable location (where the UIAlertView is shown).
The operation couldn't be completed. (Cocoa error 516)
Can anyone please tell me how to correct this error?
Thank you.
Upvotes: 1
Views: 3717
Reputation: 107131
You want to copy the file to document directory if it is not already copied to there.
In your code if the file is already there then also you are trying to copy it to the document directory. That'll result in the execution of second if(!success)
block.
Change your method like:
- (void)viewDidLoad
{
[super viewDidLoad];
BOOL success;
NSFileManager *filemngr = [[NSFileManager alloc] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDbPath = [documentDirectory stringByAppendingPathComponent:@"contacts.sqlite"];
success = [filemngr fileExistsAtPath:writableDbPath];
if(!success)
{
NSString *defaultDbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"contacts.sqlite"];
success = [filemngr copyItemAtPath:defaultDbPath toPath:writableDbPath error:&error];
if (!success)
{
[status setText:[error localizedDescription]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
Upvotes: 3