1

I am working in a project that involves fetching user uploaded post. I retrieve the user post in a dictionary and add them to an array. When the user post something, I have the creation date of the post. Now the problem comes when I load these post in a collection view where the post shuffles every time I run the code.

fileprivate func fetchPostsWithUser(user: User) {
        let ref = Database.database().reference().child("posts").child(user.uid)
        ref.observeSingleEvent(of: .value, with: { (snapshot) in
            guard let dictionaries = snapshot.value as? [String: Any] else { return }

            dictionaries.forEach({ (key, value) in
                guard let dictionary = value as? [String: Any] else { return }

                let post = Post(user: user, dictionary: dictionary)
                print(post.creationDate) // 2019-06-07 20:53:14 +0000

                self.posts.append(post)
            })


            self.collectionView?.reloadData()

        }) { (err) in
            print("Failed to fetch posts:", err)
        }
    }
Max
  • 21
  • 2

1 Answers1

1
self.posts.sort{$0.creationDate < $1.creationDate}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Max
  • 21
  • 2