Realm - Add file with initial data to project (iOS/Swift)

后端 未结 7 1465
独厮守ぢ
独厮守ぢ 2020-12-23 12:47

I\'m developing an application for iOS using swift and chose Realm as a database solution for it. I wrote default data in AppDelegate using write/add function from realm doc

7条回答
  •  不知归路
    2020-12-23 13:05

    Implement this function openRealm in AppDelegate and call it in

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
        ...
        openRealm() 
    
        return true
     }
    
    func openRealm() {
    
        let defaultRealmPath = Realm.defaultPath
        let bundleReamPath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("default.realm")
    
        if !NSFileManager.defaultManager().fileExistsAtPath(defaultRealmPath) {
            NSFileManager.defaultManager().copyItemAtPath(bundleReamPath!, toPath: defaultRealmPath, error: nil)
        }
    }
    

    It will copy your realm file that you bundled in the app to the default realm path, if it doesn't exist already. After that you use Realm normally like you used before.

    There's also the Migration example that you talked about in Swift.

    In Swift 3.0.1 you may prefer this:

        let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
        let bundleRealmPath = Bundle.main.url(forResource: "seeds", withExtension: "realm")
    
        if !FileManager.default.fileExists(atPath: defaultRealmPath.absoluteString) {
            do {
                try FileManager.default.copyItem(at: bundleRealmPath!, to: defaultRealmPath)
            } catch let error {
                print("error copying seeds: \(error)")
            }
        }
    

    (but please be careful with the optionals)

提交回复
热议问题