.realm cannot be deleted because it is currently opened

Error: Realm file at path /var/mobile/Containers/Data/Application/F9BAA6E3-2BD1-4C3E-91A8-68BD5F8846D4/Documents/mongodb-realm/dc_a360_5and6-gqsab/6051c600e1ba6508f9809bba/%22ClientCode%3D6%22.realm cannot be deleted because it is currently opened.

@Vishal_Deshai

That error is due to realm being open. Per the original question

and that’s critical. If any code touched realm in any way before deleting, it won’t work and will throw that error.

my code is:

func realmCleanup(delete: Bool = false) {
    // Invalidate progress, if set
            
    // Invalidate and clear the realm itself
    SyncRealmAllClassesV1.shared.realm?.invalidate()
    SyncRealmAllClassesV1.shared.realm = nil

    SyncRealmAllClassesV1.shared.privateRealm?.invalidate()
    SyncRealmAllClassesV1.shared.privateRealm = nil

    SyncRealmAllClassesV1.shared.userRealm?.invalidate()
    SyncRealmAllClassesV1.shared.userRealm = nil

    let curretnUser = A360R_User.login()
    let partitionValue = "ClientCode=\(curretnUser?.ClientCode ?? 0)"
    let partitionValue1 = "PUBLIC"
    let partitionValue2 = "UserCode=\(curretnUser?.UserCode ?? 0)"

    if delete {
        self.realmDelete(partitionValue: partitionValue)
        self.realmDelete(partitionValue: partitionValue1)
        self.realmDelete(partitionValue: partitionValue2)
    }
}

fileprivate func realmDelete(partitionValue: String) {
    guard let config = app?.currentUser?.configuration(partitionValue: partitionValue) else { return }
    
    // Deleting immediately doesn't work, introduce a small wait
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
        do {
            _    = try Realm.deleteFiles(for: config)
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}