2016-11-12 95 views
4

我最近升级到swift 3,并且在尝试从快照观察事件值访问某些内容时发生错误。Firebase在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 
} 

的错误是上述三个变量周围,并指出:

类型“任何”无标会员

任何帮助将不胜感激

回答

11

我认为你可能需要将你的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 ?? "" 

} 

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

7

当火力地堡返回数据,snapshot.valueAny?类型,以便您的开发者可以选择将它转换为任何数据类型,你的愿望。这意味着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 
    } 
}