Recupere apenas 5 usuários por vez: Firebase [como Instagram]

Nos últimos dias, tenho tentado criar um feed semelhante ao Instagram para o meu aplicativo. Para ser mais específico: carregue novas postagens (5) sempre que o usuário atualizar o feed da parte inferior.

Atualmente, estou usando o Firebase para armazenar e exibir meus dados.

Meu código até agora tem a seguinte aparência:

    var ref:FIRDatabaseReference!

    var dict = [String:Any]()
    var posts = [[String:Any]]()

   override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        ref = FIRDatabase.database().reference()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(animated: Bool) {

        loadValues()

    }

    func loadValues() {

        dict.removeAll()
        posts.removeAll()


        ref.child("posts").queryOrderedByChild("timeCreated").queryLimitedToLast(5).observeEventType(.ChildAdded) { (snapshot:FIRDataSnapshot) in

            if let timeCreated = snapshot.value!["timeCreated"] as? Int {
                self.dict["timeCreated"] = timeCreated
            }

            if let postText = snapshot.value!["postText"] as? String {
                self.dict["postText"] = postText
            }


            self.posts.append(self.dict)


            self.tableView.reloadData()

        }




    }


    func scrollViewDidScroll(scrollView: UIScrollView) {

        if (scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height {

            //tableView.tableFooterView!.hidden = true
            let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
            pagingSpinner.startAnimating()
            pagingSpinner.hidesWhenStopped = true
            pagingSpinner.sizeToFit()
            tableView.tableFooterView = pagingSpinner

            //loadMore(5)

        } else {

            let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
            pagingSpinner.stopAnimating()
            pagingSpinner.hidesWhenStopped = true
            pagingSpinner.sizeToFit()
            pagingSpinner.hidden = true
            tableView.tableFooterView = pagingSpinner
            tableView.tableFooterView?.hidden = true


        }


    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return posts.count

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        if let postText = posts[indexPath.row]["postText"] as? String {
            cell.textLabel!.text = postText
        }

        return cell

    }

    func loadMore(increment:Int) {

        //What should go in here?

    }

Então, o que estou tentando fazer aqui - é que estou detectando quando o usuário rolou para baixo (na minha função scrollViewDidScroll. Então, estou exibindo o indicador de atividade em sincronia e chamando a função loadMore (5), em que 5 é a quantidade de novas postagens que quero exibir.

Então aqui tenho dois problemas. A variável timeCreated é simplesmente um registro de data e hora, onde tenho dez registros (1-10, onde 10 é o mais novo e 1 é o mais antigo). Com esse código que tenho agora, o tableView exibe os dados em uma exibição ascendente, iniciando em 5 e terminando em 10.

Eu tentei reverter a matriz de dicionários (post) simplesmente executando um .reverse () antes de acrescentar o dict na função loadValues. como eu simplesmente quero que ele exiba 10 na parte superior e 5 na parte inferior.

O segundo problema que tenho é que não consigo realmente encontrar uma maneira boa e eficaz de atualizar o tableView (adicionando outros 5 registros). Eu tentei simplesmente ter apenas uma variável global com o valor padrão de 5 e, em seguida, no loadMore, basta adicioná-la às cinco e, em seguida, remover removeAll () no dict e posts - sem sorte (o tableView rola para o topo, o que eu não quero). Também tentei jogar com o queryLimitedTolast e o queryLimitedToFirst, onde acabei duplicando alguns dados.

Portanto, em outras palavras, também preciso verificar se o usuário pode realmente carregar 5 novas postagens exclusivas (ou ex. 3, se houver apenas 3 postagens exclusivas).

Alguém tem alguma idéia de como eu abordaria isso?

A ajuda seria muito apreciada, pois tenho lutado com isso nos últimos dois dias.