Realm Swift why the migration block never been called

My code is like this

class RealmDatabaseManager{
    var realm:Realm!
    let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:!
    static let shared = RealmDatabaseManager()
        let defaultURL = Realm.Configuration.defaultConfiguration.fileURL
        let realmURL = container.appendingPathComponent("default.realm")
        //check if there's file in realmurl
        let fileManager = FileManager.default

        if !fileManager.fileExists(atPath: realmURL.path) {
            try? fileManager.copyItem(at: defaultURL!, to: realmURL)
        // Config init
        let config = Realm.Configuration(fileURL: realmURL, schemaVersion: 9,migrationBlock: {migration,oldVersion in
            if oldVersion < 3 {
               migration.enumerateObjects(ofType: WordRecordRealm.className()) { oldObject, newObject in
                   if let asset = oldObject!["noteCards"] as? RealmSwift.List<WordNoteRealm>{
                       newObject!["lookUpTime"] = asset.first?.decodedObject.addTime ??
                       newObject!["lookUpTime"] =
                if oldVersion < 9{
                    migration.enumerateObjects(ofType: WordRecordRealm.className()) { oldObject, newObject in
                        let t = oldObject!["translations"]!
                        newObject!["originalTranslations"] = t
        Realm.Configuration.defaultConfiguration = config
        realm = try! Realm(configuration: config)

There are a few things that would cause it to fail but more information is needed.

Did you verify the file located at

Realm.Configuration(fileURL: realmURL

realmURL is a valid file and needs to be migrated?

When you say the migration block is never called - what isn’t called? e.g. if you add a breakpoint to your code here

let config = Realm.Configuration(

run the code and step through it line by line, at what point does it fail? And when it does, what specific thing is failing?

After some trying, this is what I found. Do you have any idea about that?

Found the solution, It turns out that my widget always init the shared object ahead of the main app environment being loaded. then I create a class

class RealmConfiguration{
    static let realmURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:!.appendingPathComponent("default.realm")
    static func getConfig()->Realm.Configuration{
        let config = Realm.Configuration(fileURL: RealmConfiguration.realmURL,schemaVersion: 40) { migration, oldVersion in
            if oldVersion < 3 {
               migration.enumerateObjects(ofType: WordRecordRealm.className()) { oldObject, newObject in
        return config

I call this function in the main app’s environment, and instead of init the widget using the shared realm object, I use @ObservedResults and set the realm default config to this config in the timeline provider’s init function. Now everything seems to work fine.