Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Preload 'Realm' DB into iOS swift3?

Tags:

ios

swift3

realm

I am trying to implement Realm database in my app , I have realm database with some Preloaded data into it . I have searched through many stack overflow resources but didn't get any success.

So far now , I have done following steps :

  1. Copy the Realm File into my app's bundle
  2. Added following code in the app delegate :

    path = Bundle.main.path(forResource: "data", ofType: "realm")
    var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath:      path!))
    config.readOnly = true
    
    // Open the Realm with the configuration
    let realm = try! Realm(configuration: config)
    

But this doesn't work , Please provide some solution to it .

Note : I don't want to migrate my database.

Thanks in advance

like image 429
Jarvis The Avenger Avatar asked Oct 27 '25 09:10

Jarvis The Avenger


1 Answers

The piece of code below works perfectly for me to load a preloaded Realm instance during the first launch of my app:

let defaultPath = Realm.Configuration.defaultConfiguration.fileURL?.path
let path = Bundle.main.path(forResource: "default", ofType: "realm")
if !FileManager.default.fileExists(atPath: defaultPath!), let bundledPath = path {
    do {
        try FileManager.default.copyItem(atPath: bundledPath, toPath: defaultPath!)
    } catch {
        print("Error copying pre-populated Realm \(error)")
    }
}
like image 104
Dávid Pásztor Avatar answered Oct 30 '25 00:10

Dávid Pásztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!