Jared Davidson Jared Davidson - 1 month ago 44
iOS Question

Grab Data, Sort Data, then Load into Table View (Swift 3 : Firebase)

I'm working on an application using Firebase. What I'm trying to accomplish is getting data from Firebase, sorting that data, and then finally loading that data into a tableView once that is done.

I'm not gonna share my whole code, but here's essentially how I want it to work:

var posts = [PostStruct]()
var following = [String]()


...

let databaseRef = FIRDatabase.database().reference()
for follower in following {
databaseRef.child("Posts").child(follower).observe(.value, with: {
DataSnapshot in
//Parse All The Data...

self.posts.insert(...)

}
}
self.posts.sort{$0.date.compare($1.date) == .orderedDescending}

print("Test")

self.tableView.reloadData()


That
print("Test")
gets called, but it gets called before the FIRDatabase is requested, so that tells me that there is absolutely no data in the tableView when it's sorting. So, I need to find a way to only sort once the Database is finished requesting.

I can put the sort and reload method in the for statement, and that works, but it loads everything up choppy, and it's not very efficient.

Answer

Not sure if this is the best way to handle this, but you could add a counter that is incremented and then execute your sort and reload code once that counter is equal to the count of the following array.

var counter = 0

let databaseRef = FIRDatabase.database().reference()
for follower in following {
    databaseRef.child("Posts").child(follower).observe(.value, with: {
        DataSnapshot in
         //Parse All The Data...

        counter += 1

        self.posts.insert(...)

        if counter == following.count {
            self.sortPosts()
        }
    }
}

func sortPosts() {
    self.posts.sort{$0.date.compare($1.date) == .orderedDescending}

    print("Test")

    self.tableView.reloadData()
}