webmagnets webmagnets - 5 months ago 70x
Swift Question

How do I get my pre-populated Default.realm file onto a device?

I have a realm file that is already populated with data that needs to be there when the app is loaded on a device.

What can I do to get the realm file onto my device for testing and what do I need to do to make sure it is already there when someone downloads the app from the app store?

I am using Swift.


Add your database file to the Xcode project, i.e. "preloaded.realm" Make sure you select the add to targets, when first dropping in your file Add to targets

Then (taking from the migration example) you can do something like this to copy that preloaded file to your default directory. This will create a read/write realm

// copy over old data files for migration
let defaultPath = RLMRealm.defaultRealmPath()
let defaultParentPath = defaultPath.stringByDeletingLastPathComponent

let v0Path = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("preloaded.realm")
NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil)
NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath, error: nil)

Here is a link to that general code https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-2.2/Migration/AppDelegate.swift