xcode 我们如何从 url 下载 sqlite 数据库并将其作为 sqlite 数据库添加到我们的应用程序中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9664558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:36:37  来源:igfitidea点击:

How can we download sqlite database from url and add it into our application as sqlite database?

iphonexcodefiledynamicbundle

提问by Nitin

I used sqlite database in my application.I want to synchronize this database with my mysql server.But i think it is easy to replace exiting database with new database in my application.So,It will also solve data import export problem.But i don't know how download .sqlite file from my url and add it into in my application bundle.

我在我的应用程序中使用了 sqlite 数据库。我想将此数据库与我的 mysql 服务器同步。但我认为在我的应用程序中用新数据库替换现有数据库很容易。所以,它也将解决数据导入导出问题。但我不不知道如何从我的 url 下载 .sqlite 文件并将其添加到我的应用程序包中。

In simple way.I want to add file in Xcode Resource folder at runtime.I don't how to do it. Please help me if anybody have idea.

以简单的方式。我想在运行时在 Xcode Resource 文件夹中添加文件。我不知道该怎么做。如果有人有想法,请帮助我。

Thanks In Advance.

提前致谢。

采纳答案by Devang

Try following code :

尝试以下代码:

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];

Now you can use this database file.

现在您可以使用这个数据库文件了。

回答by shripad20

To add downloaded database to your application as sqlite database try following code

要将下载的数据库作为 sqlite 数据库添加到您的应用程序,请尝试以下代码

NSString *dbfilepath = [FileUtils documentsDirectoryPathForResource:[NSString stringWithFormat:@"%@.db", @"downloadedDatabase"]];
NSData *dbData = [NSData dataWithContentsOfFile:dbfilepath];

NSString *filePath = [[FileUtils documentsDirectoryPath] stringByAppendingPathComponent:@"Database.sqlite"];

[dbData writeToFile:filePath atomically:YES];

Now your application database is ready with imported records.

现在您的应用程序数据库已准备好导入记录。