Populate a default Realm database with a csv file


(Mark spaulding) #1

Hi All,

Can anyone point me to a tutorial on how to populate a Realm Database with a csv file from the bundle?

Thanks for the help!
Blessings,
—Mark


(Mark spaulding) #2

In case anyone else is having trouble with this, the following works for me:

func openRealm() {
let bundlePath = Bundle.main.path(forResource: “default”, ofType: “realm”)!
let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!.path
let fileManager = FileManager.default

    // Only need to copy the prepopulated `.realm` file if it doesn't exist yet
    if !fileManager.fileExists(atPath: defaultPath){
        print("use pre-populated database")
        do {
            try fileManager.copyItem(atPath: bundlePath, toPath: defaultPath)
            print("Copied")
        } catch {
            print(error)
        }
    }

}

Migration still seems to stymie me, but at least this part works!