D. Finna D. Finna - 2 months ago 36
Swift Question

Show only posts from current user - firebase swift

I have some code that is getting every post and showing it all in a uitableviewcontroller. The code that is getting all of the posts from firebase is this:

viewDidLoad {
dbRef = FIRDatabase.database().reference().child("feed-items")
startObersvingDB()

}

func startObersvingDB() {
dbRef.observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
var newUpdates = [Sweet]()

for update in snapshot.children {
let updateObject = Sweet(snapshot: update as! FIRDataSnapshot)
newUpdates.append(updateObject)

}

self.updates = newUpdates
self.tableView.reloadData()


}) { (error: NSError) in
print(error.description)
}
}


How can I modify that part to just get updates from a specific username?
My structure in firebase is like this:

feed-items {
unique-user-id {
post: "This is a post"
byUsername: "MyUser"
}
}


So what the code should be doing, is fetching the byUsername string - I just cannot figure out how to update my code to do that. Hope you guys can help me :-)

Answer

Try this:-

Swift 3

func startObersvingDB() {
FIRDatabase.database().reference().child("feed-items").queryOrdered(byChild: "byUsername").queryEqual(toValue: "MyUser").observe(.value, with: { (snapshot: FIRDataSnapshot) in
    var newUpdates = [Sweet]()

    for update in snapshot.children {
        let updateObject = Sweet(snapshot: update as! FIRDataSnapshot)
        newUpdates.append(updateObject)

       }

       self.updates = newUpdates
       self.tableView.reloadData()


        }) { (err) in
         print(err!.localisedDescription)      
      }
   }

Swift 2

func startObersvingDB() {
FIRDatabase.database().reference().child("feed-items").queryOrderedbyChild("byUsername").queryEqualtoValue("MyUser").observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
    var newUpdates = [Sweet]()

    for update in snapshot.children {
        let updateObject = Sweet(snapshot: update as! FIRDataSnapshot)
        newUpdates.append(updateObject)

    }

    self.updates = newUpdates
    self.tableView.reloadData()


    }) { (error: NSError) in
       print(error.description)
    }
  }
Comments