Firebase访问Swift 3中的快照值错误

Roh*_*hth 5 ios firebase firebase-realtime-database swift3

我最近升级到swift 3,并且在尝试从快照观察事件值访问某些内容时遇到错误.

我的代码:

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    let username = snapshot.value!["fullName"] as! String
    let homeAddress = snapshot.value!["homeAddress"] as! [Double]
    let email = snapshot.value!["email"] as! String
}
Run Code Online (Sandbox Code Playgroud)

错误是围绕上述三个变量并指出:

类型"任何"没有下标成员

任何帮助将非常感激

小智 14

我想你可能需要把你的snapshot.value作为一个NSDictionary.

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    let value = snapshot.value as? NSDictionary

    let username = value?["fullName"] as? String ?? ""
    let homeAddress = value?["homeAddress"] as? [Double] ?? []
    let email = value?["email"] as? String ?? ""

}
Run Code Online (Sandbox Code Playgroud)

您可以查看firebase文档:https://firebase.google.com/docs/database/ios/read-and-write


esh*_*ima 8

当Firebase返回数据时,snapshot.value其类型Any?与您一样,因为开发人员可以选择将其转换为您想要的任何数据类型.这意味着snapshot.value可以是从简单的Int到偶数函数类型的任何东西.

因为我们知道Firebase数据库使用JSON树; 几乎是键/值配对,然后你需要把你snapshot.value的字典转换成如下所示的字典.

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
    {
       let username = firebaseDic["fullName"] as! String
       let homeAddress = firebaseDic["homeAddress"] as! [Double]
       let email = firebaseDic["email"] as! String

    }
    else
    {
      print("Error retrieving FrB data") // snapshot value is nil
    }
}
Run Code Online (Sandbox Code Playgroud)