Firebase swift runTransactionBlock:从“MutableData?”转换到不相关的类型“字符串”总是失败

Posted

技术标签:

【中文标题】Firebase swift runTransactionBlock:从“MutableData?”转换到不相关的类型“字符串”总是失败【英文标题】:Firebase swift runTransactionBlock : Cast from 'MutableData?' to unrelated type 'String' always fails 【发布时间】:2021-12-16 22:39:58 【问题描述】:

我需要对一个值而不是一个子值运行 transactionBlock。

数据结构:

-parent
    - child : value

当我尝试投射 MutableData 时,我会从孩子那里得到一个崩溃。 Xcode 抛出警告确认:

 Cast from 'MutableData?' to unrelated type 'String' always fails

代码片段

Database.database().reference().child("parent").child("child").runTransactionBlock( (currentData: MutableData!) -> TransactionResult in
                                        
    /**
     *
     * When runTransaction is called, it called straight away doTransaction with a supposed currentData that is the cached value and is often nil the first call.
     * Inside the doTransaction I have to make some actions based to the supposed actual data. Those actions have to work on the new value I want to set for the
     * currentData. Once that is done i send currentData gathered from currentDta.getDtata() which on the first call is just supposed and often nil and the
     * new value that i set with currentData.setData(). If the supposed current value and real current value are the same then I wite the data with the value set
     * in setData() , otherwise I do nothing and I go back with the real value I have in the database in that moment and I repeat.
     *
     *
     */
    
 
    let currentDataValue = currentData.value as! String

根据要求在屏幕截图下方:

根据官方文档,这应该是可行的:https://firebase.google.com/docs/reference/ios/firebasedatabase/api/reference/Classes/FIRMutableData

这样做的正确方法是什么?找到的所有示例都带有子 [String:Any] 我不能仅仅为了检查/写一个孩子而从父母那里截取数百万条记录。

谢谢。

【问题讨论】:

MutableData.value 可以返回多种类型,但不能返回 MutableData?。您确定错误消息来自您共享的代码吗? @FrankvanPuffelen 添加了请求的屏幕截图 【参考方案1】:

对于遇到相同情况的其他人,请参见下文

【讨论】:

以上是关于Firebase swift runTransactionBlock:从“MutableData?”转换到不相关的类型“字符串”总是失败的主要内容,如果未能解决你的问题,请参考以下文章

Firebase.google.com iOS 中的 Firebase 动态链接(Swift)

Firebase 与 Swift

无法将 Firebase 导入 Swift 类

新的 Firebase 数据导致 TableView 单元格闪烁 (Firebase/iOS/Swift)

查询和 Firebase 中的位置(swift 3)

设置值 Firebase - Swift 3