1

My app (iOS) will have a ton of data built in (and not synced to a server). I know I can take a pre-filled realm database and copy it over when the app is first used, but what I don't know is: What is the best way to build that pre-filled database?

Should modify my app, to statically create the realm database, by hardcoding all the objects and relations, then pull the database from the emulator:

 let car1 = Car(color: "red")
 ...
 let car230 = Car(color: "blue")

 ...
 try realm.write{
    realm.add(car1)
    ...
    realm.add(car230)
 }

Or is there a saner approach to this?

DataDino
  • 1,507
  • 1
  • 15
  • 30

2 Answers2

3

If the database will be always the same, I'd go for the pre-created database option due to performance. However, if you use database encryption, you'll have to do some runtime hacks.

To achieve that check out Realm Cocoa converter project (Swift or Objective-C). You can create a realm file importing from CSV, XLSX and JSON file formats.

Their example is quite clear:

var filePaths = [String]() // Array of file paths to each CSV file to include
let destinationRealmPath = '' // Path to the folder that will hold this Realm file

// Analyze the files and produce a Realm-compatible schema
let generator =  ImportSchemaGenerator(files: filePaths)
let schema = try! generator.generate()

// Use the schema and files to create the Realm file, and import the data
let dataImporter = CSVDataImporter(files: filePaths)
try! dataImporter.import(toPath: destinationRealmPath, schema: schema)

And you can check for more examples in their test project.

GoRoS
  • 5,183
  • 2
  • 43
  • 66
  • Thanks for the suggestion, I'm investigating it, but so far I am unable to get their project to run on macOS 10.12. – DataDino Feb 08 '18 at 15:26
  • Why do you need to compile their project? just use their pod in your project to get your desired Realm file: https://cocoapods.org/?q=RealmConverter – GoRoS Feb 08 '18 at 15:30
  • Yup. Tried that first, then tried compiling the project to test out the latest code. Same issue: dyld: Library not loaded: @rpath/CSwiftV.framework/Versions/A/CSwiftV – DataDino Feb 08 '18 at 15:37
  • Perhaps this issue helps you? https://github.com/realm/realm-cocoa-converter/issues/46 – GoRoS Feb 08 '18 at 15:48
  • I actually already fixed that one. I'm going to write a ticket for them, maybe I'm doing something particularly silly. +1, for the helpfulness :D – DataDino Feb 08 '18 at 15:54
2

You could create a simple app (maybe a new target within the same Xcode workspace) only to pre-fill a Realm database, run it on the simulator, open the sim folder on your system and drag the Realm file from there into your main project. Then, when the main app launches, copy the file from your bundle to a more appropriate location (such as the documents folder)

Manuel
  • 328
  • 1
  • 10