You can add your pre-populated .realm
database to your application iOS bundle as a resource (BundleResource
Build Action) and as a raw asset to your Android Asset directory (AndroidAsset
Build Action).
Using the Xamarin.Forms
-based Journal example from Realm you can add your populated database as a linked item to each native project and copy it at application startup.
Example:
In the iOS "native" project of your Xamarin.Form
solution/application, update the FinishedLaunching
method to copy your pre-populated database if the users database does NOT exist (i.e. this is the first time the application runs):
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);
}
Note: The same technique can be used in your other "native" projects
Note: A custom-written Xamarin.Forms
dependency service is an alternative to doing it this way but the results are the same
Since we are copying the prepopulated.realm
to journal.realm
within the application document directory, we can tell Realm to open this database instead of creating/using a default.realm
one.
In the Xamarin.Form
Journal project's JournalEntriesViewModel.cs
, update the code to open this journal.realm
public JournalEntriesViewModel()
{
_realm = Realm.GetInstance("journal.realm");
Entries = _realm.All<JournalEntry>();
AddEntryCommand = new Command(AddEntry);
DeleteEntryCommand = new Command<JournalEntry>(DeleteEntry);
}
Same pre-populated database in the solution linked to different "native" projects:
