将SQLite数据库从URL复制到本地路径

时间:2011-07-02 23:09:29

标签: database ios4 sqlite nsdata

我可以使用什么方法将远程数据库复制到本地路径?

success = [FileManager copyItemAtURL:dbPath toPath:databasePath error: &error];

显然上述情况不会奏效。查看手册,您似乎可以将路径或URL复制到URL。但我见过myapp的例子://path/to/documents/database.sql。现在我有点困惑。有人可能会指出我正确的方向吗?

这就是我现在正在做的事情......但它并没有覆盖数据库,或者我正在以错误的顺序做事。该文件只有几个Kbs。

- (void)createDB {
BOOL success;
NSError *error;

NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.dot.com/book/book.sqlite"]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"book.sqlite"];
[fetchedData writeToFile:filePath atomically:YES];
NSLog(@"%@", filePath);

NSFileManager *FileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingString:@"book.sqlite"];
success = [FileManager fileExistsAtPath:databasePath];
if(success)return;
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"book.sqlite"];
success = [FileManager copyItemAtPath:dbPath toPath:databasePath error: &error];
if(!success)
    NSAssert1(0, @"Failed to copy database. Error: %@", [error localizedDescription]);
}

1 个答案:

答案 0 :(得分:0)

我看到了这一行,

NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"book.sqlite"];

您正试图从 Resources 目录中获取数据库,但上面的代码实际上将sqlite直接下载到 Documents 目录而不是资源(不可写)

失败是因为资源目录中没有book.sqlite。您不需要复制该文件,因为它已存在于 Documents 目录

相关问题