Migrate from unencrypted realm to encrypted realm

喜夏-厌秋 提交于 2019-12-23 18:52:20

问题


I'm trying to migrate from unencrypted realm to encrypted but I don't know how and where to use Realm().writeCopy(toFile: url, encryptionKey: key). or even if there is another way to do it.

Thank you.


回答1:


I found a way to do that, you can find it below:

private static var realm: Realm! {

    // Get the encryptionKey
    var realmKey = Keychain.realmKey
    if realmKey == nil {
        var key = Data(count: 64)

        key.withUnsafeMutableBytes { (bytes) -> Void in
            _ = SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
        }
        realmKey = key
        Keychain.realmKey = realmKey
    }


    // Check if the user has the unencrypted Realm
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileManager = FileManager.default
    let unencryptedRealmPath = "\(documentDirectory)/default.realm"
    let encryptedPath = "\(documentDirectory)/default_new.realm"
    let isUnencryptedRealmExsist = fileManager.fileExists(atPath: unencryptedRealmPath)
    let isEncryptedRealmExsist = fileManager.fileExists(atPath: encryptedPath)


    if isUnencryptedRealmExsist && !isEncryptedRealmExsist {
        let unencryptedRealm = try! Realm(configuration: Realm.Configuration(schemaVersion: 7))
        // if the user has unencrypted Realm write a copy to new path
        try? unencryptedRealm.writeCopy(toFile: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey)
    }

    // read from the new encrypted Realm path
    let configuration = Realm.Configuration(fileURL: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey, schemaVersion: 7, migrationBlock: { migration, oldSchemaVersion in })

    return try! Realm(configuration: configuration)
}


来源:https://stackoverflow.com/questions/53539941/migrate-from-unencrypted-realm-to-encrypted-realm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!