Realm can't decrypt database error in background thread

时间:2015-10-30 22:17:14

标签: ios xcode swift realm

I am using Realm Objective-C with Swift as I am supporting iOS7 in my app.

I use a function to write a block of code to realm in a background thread. I wanted to add encryption so I modified the function as so:

  class func updateRealmWithBlockInBackground(block: () -> Void) {
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        do {
          let config = RLMRealmConfiguration.defaultConfiguration()
          config.encryptionKey = Utils.getKey()
          let realm = try RLMRealm(configuration: config)

          realm.beginWriteTransaction()
          block()
          realm.commitWriteTransaction()

        } catch {
          dispatch_async(dispatch_get_main_queue(), {
            TXNotificationSystem.postGlobalNotification(text: "\(error)", textColor: UIColor.redColor())
          })
        }
    }
  }

I am getting error code 2: Unable to decrypt realm.

If I use the one that does the write on the main thread I don't seem to be getting this error.

Anyone know why it's giving me this error ?

1 个答案:

答案 0 :(得分:0)

如果之前未对您的Realm进行过加密,则无法通过配置加密密钥来添加加密。 Realm会认为磁盘上的文件已经加密并尝试解密。

您需要在没有加密密钥的情况下打开Realm,并使用- [RLMRealm writeCopyToPath:encryptionKey:error:]编写加密副本。然后,您可以删除原始未加密的.realm文件,并使用加密密钥集打开加密副本。