Swift Realm, load the pre-populated database correctly?

I am new to ios development.

I follow this example to use a pre-populated database and change the code a bit

here is the last code i use on AppDelegate -> func application

  let defaultPath = Realm.Configuration.defaultConfiguration.path! let path = NSBundle.mainBundle().pathForResource("default", ofType: "realm") if let bundledPath = path { print("use pre-populated database") do { try NSFileManager.defaultManager().removeItemAtPath(defaultPath) try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath) } catch { print("remove") print(error) } } 

I am testing this on a real device.

It works, but according to the logic of the code, it will always be reset for a pre-populated database. This is checked: after restarting the application, the data is reset.

I tried moveItemAtPath instead of copyItemAtPath . permission error

I tried to delete a file with a populated database after copying. permission error

I tried using a pre-populated database file as the default configuration path in the real world. an error also occurs.

+7
swift realm
source share
2 answers

Yes, your logic is correct. Each time this code is run, the default Realm file in the Documents directory is deleted and replaced with the static copy included with the application. This is done using the design in the Realm sample code to demonstrate the migration process every time the application starts.

If you want this to happen only once, the easiest way to do this is to check in advance if the Realm file is already on the default path, and then make a copy only when it does not exist yet :)

 let alreadyExists = NSFileManager.defaultManager().fileExistsAtPath(defaultPath) if alreadyExists == false && let bundledPath = path { print("use pre-populated database") do { try NSFileManager.defaultManager().removeItemAtPath(defaultPath) try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath) } catch { print("remove") print(error) } } 
+1
source share

In Swift 3.0, try the following:

  let bundlePath = Bundle.main.path(forResource: "default", ofType: "realm") let destPath = Realm.Configuration.defaultConfiguration.fileURL?.path let fileManager = FileManager.default if fileManager.fileExists(atPath: destPath!) { //File exist, do nothing //print(fileManager.fileExists(atPath: destPath!)) } else { do { //Copy file from bundle to Realm default path try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!) } catch { print("\n",error) } } 
+7
source share

All Articles