Swift Realm, load the pre-populated database the right way?

后端 未结 3 577
情歌与酒
情歌与酒 2020-12-31 19:21

I\'m pretty new to ios development.

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

here is the final code I u

相关标签:
3条回答
  • 2020-12-31 19:51

    Yeah, your logic is correct. Every time this code gets executed, the default Realm file in the Documents directory is deleted and replaced with the static copy that came with the app bundle. This is done by design in the Realm sample code in order to demonstrate the migration process each time the app is launched.

    If you only want that to happen one time, the easiest way to do it would be to check beforehand to see if a Realm file already exists at the default path, and then perform the copy only when it isn't already there. :)

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-31 19:51

    try this

        let realm_db_path     = Realm.Configuration.defaultConfiguration.fileURL!
        let bundle_realm_path = Bundle.main.url(forResource: "default", withExtension: "realm")!
    
        if !FileManager.default.fileExists(atPath: realm_db_path.absoluteString){
            do {
    
                try FileManager.default.copyItem(at: bundle_realm_path, to: realm_db_path)
    
            }catch let error {
    
                NSLog(error as! String)
    
            }
    
    0 讨论(0)
  • 2020-12-31 19:54

    In Swift 3.0, try this:

        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)
            }
        }
    
    0 讨论(0)
提交回复
热议问题