D. Finna D. Finna - 12 days ago 8
Swift Question

Showing post from currentUsers wall - Firebase / Swift

I am trying to create a wall/timeline that shows posts from all the users that

currentUser
is following. All users that
currentUser
is following is showed under
Users -> UserID -> Following
. Whenever one of their followers is making a post it will be added under
feed-items
with an autoID - the key (the autoID) is added to
currentUser
s
Users -> UserID -> Wall
at the same time.

Here is an image of an example from my Firebase database:
enter image description here

Under
Wall
as you can see, one of this users followers has made a post (the whole post is saved under
feed-items
) and the autoID of that post has made it to the users Wall.

Now I am trying to figure out how to show all the posts in
feed-items
, based on the autoID's stored under
currentUser
s Wall.

I have tried the following code, but nothing shows and when it reaches this line
print(self.updates.count)
it is printing 0.

func startObersvingDB(userID: String) {

FIRDatabase.database().reference().child("Users").child(userID).child("Wall").observeEventType(.ChildAdded, withBlock: { snapshot in

if let posts = snapshot.value!["Post"] as? String {
self.postArray.append(posts)


for i in 0..<self.postArray.count {

let post = self.postArray[i]

print(post)
FIRDatabase.database().reference().child("feed-items").queryEqualToValue(post).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.reverse()
print(self.updates.count)
self.tableView.reloadData()


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

}
})

}

Answer

If I am guessing right, your structure for feed-items is something like this.

feed-items
    -UniquePostID
        -Post Data (key-value pair(s))

If this is the case then to retrieve data for a post use .child(post) instead of .queryEqualToValue(post). Also since this will return DataSnapshot for single post you can directly create your Sweet object and append it in existing updates array.

One more thing I don't think you need to iterate entire postArray each time a new post is added. You should retrieve data for new post only.

Hope this helps!!