firebase pagination with autoId
<p>Like facebook, my app has post where people can comment. I want to achieve pagination for the comments in case they become big. I am using a simple code below to test out the function. Basically, when the user hit the test button, more comments printed out. All my comments entry are saved in firebase via childByAutoId. I saw somewhere online that I can sort chronologically using the autoID as they are generated like a timestamp. Attached is my firebase entry <a href="https://i.stack.imgur.com/KCbTq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KCbTq.png" alt="firebaseEntry"></a></p>

<pre><code>@IBAction func testBtnPressed(sender: AnyObject) {

    var pageSize = 3
    var query = DataService.ds.REF_COMMENT.child(self.post.postKey).queryOrderedByKey()

    if startKey != nil {
        query = query.queryStartingAtValue(startKey)
        pageSize += 1
    }

    query.queryLimitedToFirst(UInt(pageSize)).observeSingleEventOfType(.Value) { (snapshot: FIRDataSnapshot) in
        if snapshot.exists() {
            if let comments = snapshot.value as? Dictionary&lt;String, AnyObject&gt; {

                for comment in comments {
                    let commentKey = comment.0
                    let commentDict = comment.1

                    print("commentDict \(commentDict)")

                    self.startKey = commentKey
                }
            }
        } else {
            // No comments
        }
    }
}
</code></pre>

<p>As shown in the photo, I have several comments from 1 to 16 (From top of image to bottom is comment 1, comment 2, comment 3, .... etc) That is the order when it is entered in the firebase also. </p>

<p>So what I am expecting is when I hit the test button, I will get from the commentDict printout something in the order of </p>

<p>Comment1, Comment2, Comment 3. </p>

<p>Then when i press again, I will get</p>

<p>Comment 3, Comment 4, Comment 5</p>

<p>However, On the first press I am actually getting, </p>

<p>Comment 2, Comment 1, Comment 3. </p>

<p>On the 2nd press, I am getting </p>

<p>Comment 5, Comment 4, Comment 3</p>

<p>And every press after that is</p>

<p>Comment 5, Comment 4, Comment 3</p>

<ol>
<li>Why is it not in the correct order the first time</li>
<li>Why is it showing a backward order every time after the first time?</li>
</ol>

<p>Is the AutoId not doing what it suppose to do?</p>

<p>Thanks, </p>