I am trying to make a social media feed/ wall using the UITableView with custom cells (cells called PostTableViewCell.xib) I am using this through Firebase Database. Currently I have a view controller for the feed (called HomeViewController.swift) and a separate view controller for the user to post (called NewPostViewController.swift)
My problem is every time a user made a post it would show up at the very bottom of the table and not the top like instagram, twitter, facebook would do. I was able to get around this by flipping the UiTableView and its cells 180 degrees, but now it loads that home view controller at the bottom of all the posts but the cells are now in the right order.
How can I start this home page at the top of these cells while having new cells come in at the top too. Attached is the necesary code on that homeviewcontroller:
import Foundation
import UIKit
import Firebase
class HomeViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
view.addSubview(tableView)
var layoutGuide:UILayoutGuide!
if #available(iOS 11.0, *) {
layoutGuide = view.safeAreaLayoutGuide
} else {
// Fallback on earlier versions
layoutGuide = view.layoutMarginsGuide
}
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
observePosts()
//Flips UITableView
tableView.transform = CGAffineTransform(rotationAngle: (-.pi))
}
func observePosts() {
let postsRef = Database.database().reference().child("posts")
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let author = dict["author"] as? [String:Any],
let uid = author["uid"] as? String,
let username = author["username"] as? String,
let photoURL = author["photoURL"] as? String,
let url = URL(string:photoURL),
let text = dict["text"] as? String,
let timestamp = dict["timestamp"] as? Double {
let userProfile = UserProfile(uid: uid, username: username, photoURL: url)
let post = Post(id: childSnapshot.key, author: userProfile, text: text, timestamp:timestamp)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
@IBAction func handleLogout(_ sender:Any) {
try! Auth.auth().signOut()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
//Flips cell
cell.transform = CGAffineTransform(rotationAngle: (-.pi))
return cell
}
}
The reason it is appearing at the bottom is because you are appending it here:
Append puts the new element at the end of the array. You should be inserting it at the first position like so:
Alternatively, you should be sorting the data that you are serving by the date created. Create a variable:
and then use your _posts variable.