我在iOS应用程序中使用sqlite数据库,其名称为testSqlite.sqlite。我想将其复制到应用程序文件夹。但该文件未复制到所需位置。我还添加了我的源代码。请帮忙
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths [0];
NSString *backupPath = [[NSBundle mainBundle] pathForResource:@"testSqlite" ofType:@"sqlite"];
NSLog(@"backup is %@ ",backupPath);
if (![[NSFileManager defaultManager] fileExistsAtPath: docsDir]) {
if (backupPath) {
BOOL copiedBackup = [[NSFileManager defaultManager] copyItemAtPath:backupPath toPath:docsDir error:nil];
if (!copiedBackup) {
// copying backup db failed, bail
NSLog(@"Copying backup db failed");
}
else
NSLog(@"\n\ndatabase created");
}
}
答案 0 :(得分:1)
Apple建议使用网址,以下代码可在我的应用中使用:
NSString *docDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docDirectory stringByAppendingPathComponent:@"testSqlite.sqlite"];
NSURL *fileDocURL = [NSURL fileURLWithPath:[docDirectory stringByAppendingPathComponent:@"ProductInventory.plist"]];
NSURL *newFileURL = [NSURL fileURLWithPath:filePath];
NSLog(@"fileDocURL: %@, newFileURL: %@", fileDocURL, newFileURL);
NSError __autoreleasing *error;
BOOL success = [[NSFileManager defaultManager] copyItemAtURL:fileDocURL toURL:newFileURL error:&error];
if (success) {
NSLog(@"Transaction file was copied");
// Delete the old file
[[NSFileManager defaultManager] removeItemAtURL:fileDocURL error:nil];
} else {
NSLog(@"NO transaction file to copy, Error: %@", [error localizedDescription]);
}
答案 1 :(得分:0)
尝试使用此代码将主程序包复制到运行时的文档目录文件夹。
NSString *pathsToReources = [[NSBundle mainBundle] resourcePath];
NSString *yourOriginalDatabasePath = [pathsToReources stringByAppendingPathComponent:@"lunchDB.sqlite"];
NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [pathsToDocuments objectAtIndex: 0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"lunchDB.sqlite"];
if (![[NSFileManager defaultManager] isReadableFileAtPath: dbPath]) {
if ([[NSFileManager defaultManager] copyItemAtPath: yourOriginalDatabasePath toPath: dbPath error: NULL] != YES)
NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, dbPath);
}
替换你的文件名" lunchDB.sqlite"这里。 感谢。