I'm seeking to populate the tableview of my users with the last message they sent or were sent just like the initial View on Messages App on iphone. I have this code but it doesn't work to iterate through the array of dictionaries that I keep snapshots in of all the messages that were sent to the user and return the expected result:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
func getMsg()-> Int{
var getIndex = Int()
let messageDb = Database.database().reference().child("iMessenger/Messages")
messageDb.observe(.childAdded) { (snapshot) in
if let snapshotvalue = snapshot.value as? [String:Any], let sender = snapshotvalue["sender"] as? String, let key = snapshotvalue["key"] as? String{
// I thought that I could iterate through my array of dictionaries taking care to find a matching sender value for the user at indexpath.row and the key for the message
for (index, dict) in newMessageDictArr.enumerated(){
if self.users[indexPath.row].userPhone == sender && dict["key"] == key{getIndex = index}}}}
return getIndex}
if newMessageDictArr.count != 0{
cell.userMessage.text = newMessageDictArr[getMsg()]["messageBody"]}
return cell}
The problem I'm having with the code is that
cell.userMessage.text = newMessageDictArr[getMsg()]["messageBody"]
Makes all my cells have the first value for ["messageBody"] so it's like all my users seemed to have sent me the same message. Trying to figure out where I went wrong...
Also here's my FireBase structure, thanks.
{
"iMessenger" : {
"Messages" : {
"-KxDSQOBuCkpFdw4SPDh" : {
"messageBody" : "TEST ",
"receiver" : "+197862",
"sender" : "+16698"
},
"-KxBjNM_iA2XaapyyC9o" : {
"key" : "-KxBjNM_iA2XaapyyC9o",
"messageBody" : "TEST",
"receiver" : "+197862",
"sender" : "+1914862"
},
"Messages+199862+197862" : {
"-KxB7P-vgdfxRpSdnwCT" : {
"messageBody" : "yo, wassup world",
"receiver" : "+197862",
"sender" : "+199862"
},
"-KxB81fbn5_OHxdj4lcA" : {
"messageBody" : "Hello World",
"receiver" : "+19147862",
"sender" : "+1997862"
}
},
"Users" : {
"-Kx41o03NIMBR68F2sCS" : {
"displayName" : "sleeping beauty ",
"firstName" : "",
"lastName" : "",
"phoneNumber" : "+165698"
},
"-Kx42IXgN1z9D5Zoz0fk" : {
"displayName" : "KarmaDeli",
"firstName" : "",
"lastName" : "",
"phoneNumber" : "+1397862"
}}}}