Reputation: 6110
I'm making an app where I need to copy certain file from the app bundle to the user's Application Support folder. This is the code I'm using actually:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName]; // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:@"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager copyItemAtPath:[thisBundle pathForResource:@"db" ofType:@"sqlite"] toPath:saveFilePath error:NULL];
But this doesn't copies anything, BTW this is a Mac app.
Upvotes: 2
Views: 4387
Reputation: 6110
Finally got it working with adding
if ([fileManager fileExistsAtPath:userpath] == NO)
[fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
And the resulting code is:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName]; // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:@"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:userpath] == NO)
[fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager copyItemAtPath:[thisBundle pathForResource:@"db" ofType:@"sqlite"] toPath:saveFilePath error:NULL];
Upvotes: 5
Reputation: 796
You might want to double-check your file paths:
NSLog(@"src: %@", [thisBundle pathForResource:@"db" ofType:@"sqlite"]);
NSLog(@"dst: %@", saveFilePath);
Upvotes: 0