0

Having a hard time figuring out how to iterate through the my messages database so I can find a key that matches a user's phone number... this method crashes and all the other ways I've tried fail as well. I could really use the help thanks.

 func retrieveMessages(){
    let messagesDB = Database.database().reference().child("iMessenger/Messages")

    messagesDB.observe(.childAdded, with: {(snapshot) in
    let snapshotValue = snapshot.value as! Dictionary<String, String>

    //This conditional is suppose to filter out messages that aren't to or from the user
    if snapshotValue["sender"]! == userPhoneNumber || snapshotValue["receiver"]! == userPhoneNumber{

    let text = snapshotValue["messageBody"]!
    let sender = snapshotValue["sender"]!

    let message = Message()
    message.messageBody = text
    message.sender = sender

    self.messageArr.append(message)
    self.configureTableView()

    self.messagesTableView.reloadData()
    self.scrollToLastRow()}}

)}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
KarmaDeli
  • 610
  • 1
  • 6
  • 16

1 Answers1

0

You should not use ! in your code as much as possible, it is bound to crash if the value is nil and I think you need to downcast the value to String to compare the phone numbers, so you can modify your code as follows: (use optional binding and downcasting)

if let snapshotValue = snapshot.value as? [String: Any], let senderNumber = snapshotValue["sender"] as? String,let receiverNumber = snapshotValue["receiver"] as? String  {

        //now you should compare these values as follows...
        if senderNumber == userPhoneNumber || receiverNumber == userPhoneNumber {
             //do your stuff...

        }

}
3stud1ant3
  • 3,586
  • 2
  • 12
  • 15
  • YES! that did the trick thanks. I know I should be more careful with optionals but I was sure my database had the value I was querying, or so i thought. Going forward I'll keep this experience in mind and optional bind wherever possible. – KarmaDeli Oct 24 '17 at 05:03
  • @KarmaDeli please accept the answer, if it solves your problem, thanks – 3stud1ant3 Oct 24 '17 at 06:00
  • Done. Thanks again. I'm still new to stackoverflow i tried to support your answer by upvoting and thought that would do it but it's really the check mark I should of clicked. – KarmaDeli Oct 24 '17 at 11:07
  • Will do, started learning in May and it's been equal parts challenging and fun. I asked a sort of follow question to this one-- I'd appreciate if you could lend some of your expertise on that one as well: https://stackoverflow.com/questions/46915747/populate-tableviewcells-with-snapshot-values-in-swift – KarmaDeli Oct 24 '17 at 16:45