-2

I'm using the message Kit. In a chatDashbaord extension I've boolean condition like if the isnewConversation contain true then call the function insertConversation2 and if isnewConversation contain false then call the function sendMessag.But I've checked using the break points the code is not going to isNewconversation block and I don't know why it's happening.When I'm not using the boolean statement the code working file and append the data into an array please check the code thanks.

MessageViewController:

 class ChatDashboard: MessagesViewController {
        var userActive: String? = nil
        var receiverName:String? = nil
        var isnewConversation = false
        var recevierName:String? = nil
        var otheruserEmail: String? = nil
        var conversationId:String? = nil
        var messages : [Message] = []{
            didSet{
                DispatchQueue.main.async {
                    self.messagesCollectionView.reloadDataAndKeepOffset() 
            }
        }
    

extension ChatDashboard:

 extension ChatDashboard: InputBarAccessoryViewDelegate{
 
        
        func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
            guard !text.replacingOccurrences(of: "", with: "").isEmpty,let selfSender =
                    self.selfSender,let  messageId = createMessageId() else{
                return
            }
            
            let message = Message(sender: selfSender, messageId: messageId, sentDate: Date(), kind: .text(text))

            
            guard let otheruserEmail = otheruserEmail,let recevierName = recevierName else {return}
        
          if isnewConversation{
                NetworkingService.shared.insertConversation2(with:otheruserEmail,name:recevierName, message: message) { (success) in
                    if success{
                        print("message Send")
                        self.isnewConversation = false
                    }
                    else{
                        print("not send")
                    }
                }
        }
            
         else{
            guard let converId = conversationId else {return}
            NetworkingService.shared.sendMessage(converId,recevierName,message) { (success) in
                if success{
                    print("message send in")
                }
                else{
                    print("message not send")
                }
            }

        }
            
        }

}

}

SendMessage func code when condtion false:

 func sendMessage(_ convesationId:String,_ name:String,_ message:Message,completion:@escaping(Bool) -> Void){
    
    self.sendMessageReciverToSender(convesationId) { (user) in
        guard var receiverToSenderNdoe = user else {completion(false); return}
        let dformatter = DateFormatter()
        dformatter.dateFormat = "dd/MM/yyy HH:mm"
        let dateToString = dformatter.string(from: Date())
        guard let email = UserDefaults.standard.value(forKey: "useremail") as? String else {
            print("Email not found in user default")
            completion(false)
            return
        }
        let currentUserEmail = getUserEmail(currentEmail: email)
            var messageData = ""
            switch message.kind{
            case .text(let messageText):
                messageData = messageText
            default:
                break
            }
            let newMessge: [String:Any] = [
                "id":message.messageId,
                "type":message.kind.messageKindString,
                "content":messageData,
                "date": dateToString,
                "sender_email":currentUserEmail,
                "is_read":false,
                "name":name
                
            ]
            
        //issues is here 
        if var conversationData = receiverToSenderNdoe["messages"] as? [[String:Any]]{
            conversationData.append(newMessge)
            receiverToSenderNdoe["messages"] = conversationData
            self.reciverToSenderSave(convesationId, newMessge) { (result) in
                if result{
                    completion(true)
                }
                else{
                    completion(false)
                }
            }
        }
        
        
    }

}

Inside the sendMessage func this two function called

func sendMessageReciverToSender(_ conversationId:String,completion:@escaping([[String:Any]]?) -> Void){
    database.child("\(conversationId)/messages").observeSingleEvent(of: .value) { (snapshot) in
        if let currentUser = snapshot.value as? [[String:Any]]{
            completion(currentUser) 
        }
        else{
            print("errro in reciver to sender sendMessageReciverToSender func ")
            completion(nil)
        }
    }
}

func reciverToSenderSave(_ conversationId:String,_ conversation:[[String:Any]],completion:@escaping(Bool)-> Void){
    database.child("\(conversationId)/messages").setValue(conversation){(error,ref) in
        if error == nil{
            completion(true)
        }
        else{
            print("eroor in receiptin \(error?.localizedDescription)")
            completion(false)
        }
        
    }
}
Faheem
  • 97
  • 5

1 Answers1

1

Your sendMessage has return without calling completion here

guard var receiverToSenderNdoe = user else {return}

Should be

guard var receiverToSenderNdoe = user else { completion(false) ; return } 

And here

guard let email = UserDefaults.standard.value(forKey: "useremail") as? String else {
   print("Email not found in user default") 
   return
}

Should be

guard let email = UserDefaults.standard.value(forKey: "useremail") as? String else {
   print("Email not found in user default")
   completion(false)
   return
}

You have to make sure all paths are handled so to have your callback called in success/failure , BTW something like this

if result{
  completion(true)
}
else{
  completion(false)
}

Could be shortly

completion(result)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Safer to use `defer { completion(someResult) }` – Rob C Sep 29 '21 at 03:24
  • @Sh_Khan I've applied your code but still the boolean condition is not working.I've checked through break points still same result .When guard let otheruserEmail = otheruserEmail,let recevierName = recevierName else {return} and not going to next line like if isNewConversation{} else{} and termianted – Faheem Sep 29 '21 at 12:42
  • @Sh_Khan I've found the issue in sendMessage function where the two function is also called sendMessageReciverToSender and reciverToSenderSave on the sendMessageReciverToSender func in firebase there is a conversation id and inside the id there is an message array so i want to append the data here .check the completion handler it's fine or not or also checking when i calling the this two function in sendMessage func I think I'm wrong that's the main issue please check – Faheem Sep 29 '21 at 14:20