0

I'm passing data from one controller to another using a segue. What's strange is that the second view controller is able to detect the data value in one part of the code and throwing a "Unexpectedly found nil while unwrapping an Optional value" error in another part. Can someone help?

View Controller 1: Passing data to View Controller 2

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showMsg" {
        
       let nav = segue.destination as! UINavigationController
       let VC = nav.topViewController as! MessagesViewController
                if let ref = ref {
                        DatabaseConnect.fetchTransactionUser(ref: ref, completion: { (user) in
                            if let user = user {
                                VC.userId = "Data passed"

                            }
                        })
                }
    }
}

View Controller 2: Retrieving data from View Controller 1

  var userId:String?
  func fetchFeed() {
  
  let message = Database.database().reference().child("allmessages").child(currentUser).child(userId!) //ERROR HERE!
        message.observe(.value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let postId = value?["postId"] as? String ?? ""
        })
  }

  //meanwhile, later in the file, this action is working below for some reason
    @IBAction func postCommentAction(_ sender: Any) {
    var commentText = ""
    
    if let text = textFieldLabel.text {
        
       commentText = text
        
    }
    
    if commentText != "" {
        
        let currentUser = Auth.auth().currentUser!.uid
                    
        let messageIdExist = Database.database().reference().child("allmessages").child(currentUser).child(userId!) //THIS WORKS!
                    
                    messageIdExist.observeSingleEvent(of: .value, with: { (snapshot) in
                         
                           })
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
john smith
  • 85
  • 2
  • 9
  • 1
    You know that `VC.userId = "Data passed"` will be set later, not "directly", right? Because there is the asynchrone concept behind it. – Larme Jul 14 '21 at 08:26
  • 1
    Add a log before `VC.userId = "Data passed"` => `print("VC.userId will be set"); VC.userId = "Data passed"`, and check when this output/print appears in your console vs when `fetchFeed()` is called (add also a print in `fetchFeed()`) – Larme Jul 14 '21 at 08:27
  • What does a guy named 'DatabaseConnect' come from? What does another guy named 'fetchTransactionUser' come from? – El Tomato Jul 14 '21 at 08:30
  • How do I fix the async problem Larme? – john smith Jul 14 '21 at 08:57

0 Answers0