2016-11-11 136 views
5

我試圖獲得createdAt等於Today的所有條目,但它不返回任何內容。用Swift 3.0查詢Firebase

我在這裏做錯了什麼?而且,以我想要做的方式查詢數據的正確方法是什麼?

JSON:

{ 
     "thoughts" : { 
     "-KWGdcdZD8QJSLx6rSy8" : { 
      "createdAt" : "Tomorrow", 
      "thought" : "meno", 
      "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" 
     }, 
     "-KWGeGivZl0dH7Ca4kN3" : { 
      "createdAt" : "Today", 
      "thought" : "meno", 
      "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" 
     }, 
     "-KWGeIvWHBga0VQazmEH" : { 
      "createdAt" : "Yesterday", 
      "thought" : "meno", 
      "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" 
     } 
     } 
    } 

斯威夫特:

let db = FIRDatabase.database().reference().child("thoughts") 
    let ref = db.queryEqual(toValue: "Today", childKey: "createdAt") 

    ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in 
     for snap in snapshot.children { 
      print((snap as! FIRDataSnapshot).key) 
     } 
    }) 

回答

8

您需要使用queryOrderedByChildcreatedAt比使用equalTo Today

let ref = FIRDatabase.database().reference().child("thoughts").queryOrdered(byChild: "createdAt").queryEqual(toValue : "Today") 

ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in 
    for snap in snapshot.children { 
     print((snap as! FIRDataSnapshot).key) 
    } 
}) 
+0

更新該行其他任何人有這個問題: 'let ref = db.queryOrdered(byChild:「createdAt」)。queryEqual(toValu e:「Today」)' –

+0

@ColbyGatte我剛剛編輯了引用行...請你再試一次 –

+0

嗨@ EICaptainv2.0,我實現了你的答案,但是我得到了所有的子節點。我使用的是.childAdded而不是.value,並且我得到了所有的子值,而不僅僅是匹配查詢的那些值(我用Int時間戳命令,並且使用queryStarting(at :)。你可以擺脫。 – Septronic