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
})