0

I have a path that I run a Transaction on. I check to see if the value is nil before proceeding. If it is nil I abort and if not I continue. The issue is the value isn't nil but the mutable data is saying it is.

db:

@posts
   @postId_abc
      -date: ....
      -views: 0

Transaction:

let viewsPath = Database.database().reference()
                   .child("posts")
                   .child("postId_abc")
                   .child("views")

viewsPath.runTransactionBlock({ (mutableData: MutableData) -> TransactionResult in

    let doesViewsExist = mutableData.value as? Int // I also tried Double
    if doesViewsExist == nil {
                        
        return TransactionResult.abort() // "views" value is 0
    }

    // ...
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

1 Answers1

0

This is the expect behavior. When you start a transaction the SDK immediately calls your transaction handler with its best guess of the current value of the node. Most often that guess will be nil, as the client has no better knowledge yet.

So you will have to not abort the transaction, but instead set another value on the mutable data, for example 0. It doesn't really matter much what that value is, as the transaction will be retried anyway.

For more background on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807