开发者

Copy SQLite Database from URL to Local Path

What can I use to copy a remote database to a local path?

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

Obviously the above won't work. Looking at the manual it seems you can copy path to path or url to url. But I've seen example of myapp://path/to/documents/database.sql. Now I'm sorta confused. Can someone possibly point me in the right direction?

This is what I'm doing right now... but it's not overwriting the database or I'm doing things in the wrong order. The file is only a couple of Kbs also.

- (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]);
}


I see by the line,

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

you are trying to get the db from Resources directory, but your code above actually downloads the sqlite directly to Documents directory NOT resources (which is not writable)

It fails because there is no book.sqlite at resources directory. You don't need to copy the file since it is already present in Documents directory

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜