Pfil Mintz
Pfil Mintz

Reputation: 161

Firebase child listener on child moved

I am trying to rearrange items in list through firebase child moved in firebase child listener. But the item to be moved replaces the item at the new position. The sorting is however than properly when I scroll up and down

      query.observe(.childMoved) { dataSnapshot in
        if let value = dataSnapshot.value as? [String: Any],
            let index = self.friends.index(where: {$0.fuid == dataSnapshot.key}) {
            let indexPath = IndexPath(item: index, section: 0)
            
            let movedPost = friendsModel(snapshot: dataSnapshot)
            
            self.friends.remove(at: index)
            self.friends.insert(movedPost, at: 0)
            
            self.tableView.reloadRows(at: [IndexPath(item: 0, section: 0)], with: .none)
            self.tableView.reloadRows(at: [indexPath], with: .none)
            
        
    }
    
   
    }

Upvotes: 0

Views: 194

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Your .childMoved listener gets called with the DataSnapshot that was moved and the previousSiblingKey, which is the key of the item after which you need to reinsert the snapshot in your friends list. Since your code doesn't use previousSiblingKey, it doesn't have enough information to process the move correctly.

See the Firebase documentation: https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DatabaseQuery#observe_:andprevioussiblingkeywith:withcancel:

Upvotes: 1

Related Questions