2016-11-12 94 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 
    } 
}