Search code examples
swiftrealm

Issue with copying existing realm database in swift


I have a realm db and I am trying to copying it in swift project. The Database is getting copied data successfully but it makes one column empty and separate it from other database and place it at end as empty column. Database base before copying is like this. and after copying is like this. I am unable to understand this behaviour code for copying db is.

 guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let finalDatabaseURL = documentsUrl.appendingPathComponent("default.realm")

    do {
        if !fileManager.fileExists(atPath: finalDatabaseURL.path) {
            if let dbFilePath = Bundle.main.path(forResource: "default", ofType: "realm") {
                try fileManager.copyItem(atPath: dbFilePath, toPath: finalDatabaseURL.path)
            } else {
                print("db not in the app bundle")
            }
        } else {
            print("Database file found at path: \(finalDatabaseURL.path)")
        }
    } catch {
        print("Unable to copy: \(error.localizedDescription)")
    }

Solution

  • It doesn't appear that's the same database or a copy of it: the Column names are different - in one screen shot it's Sub_category and the second screen shot it's sub_category note the capital 'S' vs lowercase 's'.

    Take look at your Realm model definition or perhaps examine your migration code if you have any. I don't think the code in the question is related to the issue you're describing.