您可以将预先填充的 .realm 数据库作为资源 (BundleResource Build Action) 添加到您的应用程序 iOS 包中,并作为原始资产添加到您的 Android 资产目录 (AndroidAsset Build Action)。
使用 Realm 中基于 Xamarin.Forms 的 Journal 示例,您可以将填充的数据库作为链接项添加到每个本机项目并在应用程序启动时复制它。
示例:
如果用户数据库不存在(即这是应用程序第一次运行时):
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
var prepopulated = "prepopulated.realm";
var realmDB = "journal.realm";
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (!File.Exists(Path.Combine(documentsPath, realmDB)))
{
File.Copy(prepopulated, Path.Combine(documentsPath, realmDB));
}
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
注意:同样的技术可以用在你的其他“原生”项目中
注意:自定义编写的 Xamarin.Forms 依赖服务可以替代这种方式,但结果是一样的
由于我们在应用程序文档目录中将prepopulated.realm 复制到journal.realm,我们可以告诉Realm 打开这个数据库,而不是创建/使用default.realm 一个。
在Xamarin.Form Journal 项目的JournalEntriesViewModel.cs 中,更新代码以打开此journal.realm
public JournalEntriesViewModel()
{
_realm = Realm.GetInstance("journal.realm");
Entries = _realm.All<JournalEntry>();
AddEntryCommand = new Command(AddEntry);
DeleteEntryCommand = new Command<JournalEntry>(DeleteEntry);
}
解决方案中的相同预填充数据库链接到不同的“本地”项目: