webmagnets
webmagnets

Reputation: 2296

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.

Upvotes: 2

Views: 3571

Answers (2)

yoshyosh
yoshyosh

Reputation: 14086

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

Upvotes: 8

jpsim
jpsim

Reputation: 14409

You'll first have to create the realm file you want to ship with your app. Once you have that, add it to your app's Xcode project and copy it into the bundle (which Xcode should do automatically).

At this point, the app should be able to access the bundled file (you can use NSBundle.mainBundle().pathForResource(_:ofType:) to get the path).

You can either create a read-only realm at this path (see RLMRealm(path:readOnly:error:)), or copy it to your Documents directory to create a read-write realm file.

You should refer to our migration example for more details on how to do this.

Upvotes: 3

Related Questions