I have tried everything but data is not coming in order , even snapshot is showing data in unordered form
I'm developing chat app. i want to maintain the order of the data so chat must show in order, but its not happening. whenever i send message it placed between the old messages not in the bottom
Here the latest message "what are you doing?"
here's the chat. look where is that latest message "what are you doing?"
my code for observing messages
public func getAllMessagesForConversation(with id: String, completion: @escaping (Result<[Message], Error>) -> Void) {
database.child("\(id)").queryOrdered(byChild: "date").observe(.value) { (snapshot) in
guard let value = snapshot.value as? [String:Dictionary<String, Any>] else{
completion(.failure(DatabaseError.failedToFetch))
return
}
var messages = [Message]()
for i in value {
guard let message = i.value["message"] as? String else {return}
let senderId = i.value["sender"] as? String
let recieverId = i.value["reciever"] as? String
let messageID = i.value["id"] as? String
var DATE = Date()
if let date = i.value["date"] as? String {
DATE = ChatViewController.dateFormatter.date(from: date)!
}
var kind: MessageKind?
kind = .text(message)
let finalKind = kind
let sender = Sender(photoURL: "",
senderId: senderId!,
displayName: Api.Params.inputUserName)
let abc = Message(sender: sender,
messageId: messageID ?? "",
sentDate: DATE,
kind: finalKind!)
messages.append(abc)
if messages.count == value.count {
messages = messages.sorted(by: { (lhs, rhs) -> Bool in
lhs.sentDate.toMillis() > rhs.sentDate.toMillis()
})
}
print(messages)
}
completion(.success(messages))
}
}