2016-11-08 61 views
0

我正在通過Udemy上的一門課程構建與Firebase,Backendless和Swift的聊天應用程序。所有的問題(它是爲Swift 2而不是3寫的)我已經能夠解決我自己,但是這一個讓我難住。這個函數應該從Firebase數據庫中檢索數據,顯然它應該將它作爲一個NSArray檢索出來,但是現在它將它作爲一個NSDictionary進行檢索,它在其他函數中製作了大量的錯誤列表,因爲它並不期待字典。從Firebase檢索並讀取數據作爲NSArray(Swift 3)

func loadRecents() { 
firebase.childByAppendingPath("Recent").queryOrderedByChild("userId").queryEqualToValue(currentUser.objectId).observeEventType(.Value, withBlock: { 
     snapshot in 
     self.recents.removeAll() 
     if snapshot.exists() { 
      let sorted = (snapshot.value.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptior(key: "date", ascending: false)]) 
     } 
    }) 
} 

我儘量更新,斯威夫特3爲:

func loadRecents() { 
    ref = FIRDatabase.database().reference() 
    let userId = currentUser?.getProperty("username") as! String 
    ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: { 
     snapshot in 
     self.recents.removeAll() 
     if snapshot.exists() { 
      let values = snapshot.value as! NSDictionary 
     } 
    }) 
} 

當然,使用as! NSArray不起作用。如果有人能提出一個方法來更新它來使用Swift 3,按照數據中的值對它進行排序,並且能夠稍後訪問它,我們將非常感激。謝謝!

回答

2
func loadRecents() { 
ref = FIRDatabase.database().reference() 
let userId = currentUser?.getProperty("username") as! String 
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: { 
    snapshot in 
    self.recents.removeAll() 
    if snapshot.exists() { 
     let values = snapshot.value as! [String:AnyObject] 
    } 
})} 

,或者您可以使用也let values = snapshot.value as! [Any]

+0

謝謝,這個幫助,但我從做更多的研究看,我應該在snapshot.children中使用'for child'讓myvalue = child.value [「my value」] as!字符串 }'或類似的東西來梳理子節點。但是,當我這樣做時它說「NSFastEnumerationIterator沒有元素值」,那麼它建議我把它投到AnyObject,但當然這也不起作用。你知道如何做這個工作嗎? –

+0

@EthanT首先你必須檢查「子」返回類型做調試模式 – ItsMeMihir

1

希望這會幫助你,試試這個代碼:

func loadRecents() { 
    let ref = FIRDatabase.database().reference() 
    let userId = currentUser?.getProperty("username") as! String 
    ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: { 
     snapshot in 
     self.recents.removeAll() 
     guard let mySnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] else { return } 
     for snap in mySnapshot { 
      if let userDictionary = snap.value as? [String: Any] { 
       print("This is userKey \(snap.key)") 
       print("This is userDictionary \(userDictionary)") 
      } 
     } 
    }) 
}