First impression matters.

When a user installs your app for the first time, they expect to see some data to interact with. If your app is a to-do list, a note-taking app, or a recipe app, the user would expect to see some sample data to understand how the app works.

You can preload demo data into your app to give users a head start. This initial data could be a set of default values, sample data, or even user-specific data.

Different Ways to Preload Demo Data

Let us look at the different ways to do this, and the advantages and drawbacks of each approach.

Storing the Data in a JSON File

You can bundle a JSON, plist, or CSV file, with the initial data, into the app. When the database is opened for the first time, you can read the file and populate the database.

This approach is simple and gets the job done. You can easily update the initial data by updating the file.

The drawback is that you need to write code to read the file and populate the database. This can be cumbersome if the data is complex or if you have a large dataset.

Populating Database from Code

Another approach is to write code to populate the database with the initial data. This does not require reading a file, but you need to write code to create objects and relationships.

This approach is flexible and allows you to create complex data structures. You can also customize the data based on user preferences or app settings.

The drawback is that you need to write code to create the initial data. This can be time-consuming and error-prone, especially for large datasets.

Using Realm Swift’s Seed File Feature

When using Realm Swift framework, we can use the seedFilePath property in the Realm configuration to seed the database with initial data. This requires a local file path to the Realm database file with the initial data.

This approach is simple and efficient. The initial data is loaded automatically when the database is opened for the first time. If the database is already created and not empty, the seed file is not used. It requires much less code compared to the other methods.

The drawback is that the initial data cannot be customized based on user preferences or app settings. Also, you need to create a separate Realm database file with the initial data and include it in the app bundle.

But even with these minor limitations, this is a great option for most apps that need to preload demo data, and requires just two simple steps:

  1. Creating a Realm database file with the initial data
  2. Seeding the Realm database with the data file.

Create a Realm Database File with Initial Data

The first step is to create a Realm database file with the initial data. You can create this file using the Realm Studio app or programmatically.

In the following example, let us create a Realm database file with a Task object.

import RealmSwift

final class Task: Object {
    @Persisted var name: String = ""
    @Persisted var isCompleted: Bool = false

    convenience init(name: String) {
        self.init()
        self.name = name
    }
}

let initialTasks: [Task] = [
    Task(name: "Buy groceries"),
    Task(name: "Pay bills"),
    Task(name: "Call mom")
]

do {
    // Configuration for the Realm database file with initial data
    let demoTasksDBConfiguration = Realm.Configuration(
        fileURL: Realm.Configuration.defaultConfiguration.fileURL!
            .deletingLastPathComponent()
            .appendPathComponent("demoTasksDB.realm")
    )
    
    let realm = try Realm(configuration: demoTasksDBConfiguration)
    try realm.write {
        realm.add(initialTasks)
    }

    // Print the file path of the Realm database
    print("Demo DB file path: \(demoTasksDBConfiguration)")
} catch {
    print("Error seeding initial data: \(error)")
}

The above code initializes a Realm database file demoTasksDB.realm with three tasks. The file is saved in the app’s document directory and file path is printed to the console. Once the file is created, the code can be removed from the app.

You can use the Realm Studio app to view the contents of the demoTasksDB.realm file.

Copy this file to your Xcode project to include it in the app bundle.

Seed Realm With Initial Data

To seed the Realm database with initial data, you need to create a realm configuration. Set the seedFilePath property to url of the demo data file.

import RealmSwift

// URL of the Realm database file with initial data
let seedFilePath: URL = Bundle.main.url(forResource: "demoTasksDB", withExtension: "realm")

// URL of the Realm database file used by the app
let tasksDBFilePath: URL = Realm.Configuration.defaultConfiguration.fileURL!
    .deletingLastPathComponent()
    .appendPathComponent("TasksDB.realm")

// Configuration for the Realm database with seedFilePath
let config = Realm.Configuration(
    fileURL: tasksDBFilePath,
    seedFilePath: seedFilePath
)

// Open the Realm database
do {
    let realm = try Realm(configuration: config)
    print("Realm seeded with initial data")
} catch {
    print("Error seeding Realm with initial data: \(error)")
}

The above code creates a configuration with the seedFilePath property set to the URL of the demoTasksDB.realm file. When the Realm database is opened, the initial data from the seed file is used if the database is empty.

Now, when the app is launched for the first time, the Realm database is seeded with the initial data. If the database already contains data, the seed file is not used.

You can verify this by opening the TasksDB.realm file in the app’s document directory using the Realm Studio app and checking if the initial data is present.

Points to Note

  • The seedFilePath property can be used to seed disk-based Realms (ones written to disk) as well as in-memory Realms (which persist only in memory).

  • seedFilePath expects a local file path. So the easiest option is to include the seed file in the app bundle.

    However, you do have the option of downloading the seed file from a server and saving it to the app’s document directory. You can then use the local file path to seed the Realm database.

    This approach is useful when you want to update the initial data without updating the app. But remember to handle the case when the seed file is not available.

  • The seedFilePath property is used only if the Realm database is opened for the first time.

    For a disk-based Realm, the seed file is used only if the database file is not present. If the database file is present but empty, the seed file is not used.

    For an in-memory Realm, the seed file is used only if the Realm is not already open.