我使用这段代码加载本地sqlite数据库。从URL下载sqlite数据库
- (id)init
{
self = [super init];
if (self) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"db" ofType:@"sqlite3"];
_db = [[MDDatabase alloc] initWithPath:path];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
我想使数据库联机并让应用程序下载数据库。我改变了代码:
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
Editted: 我改变了我的代码遵循但它的坠毁。
- (id)init
{
self = [super init];
if (self) {
[self performSelectorOnMainThread:@selector(downalod) withObject:nil waitUntilDone:YES];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
-(void)download
{
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
}
有用于获取正确的文档文件夹中引用的例子不胜枚举。请在'NSDocumentDirectory'上搜索。 – rmaddy