Ian Ian - 1 month ago 5
iOS Question

passing value from VC1 to VC2

I am now passing value from VC1 to VC2

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

if indexPath.row == 0 {

FIRDatabase.database().reference().child("Menus/Day1").observeSingleEvent(of: .value, with: {(snap) in

if let snapDict = snap.value as? Dictionary <String, AnyObject>{

let date = snapDict["mealPic"] as! String

let OrderInfo = DataService.ds.REF_ORDER
let USERUID = FIRAuth.auth()!.currentUser!.uid
let userinfo = OrderInfo.child(date).child(USERUID).child("data")

self.valueToPass = date
}
})
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if(segue.identifier == "ToVari") {
var Vari = segue.destination as! Variation
Vari.passedValue = valueToPass
}
}


and my VC2 viewDidLoad:-

var passedValue : String!

override func viewDidLoad() {
super.viewDidLoad()

MEALDATE.text = passedValue


// Do any additional setup after loading the view.
}


It actually worked but the weird thing is the "passedValue" in VC2 didn't show at first (I select cell in VC1 to performSegue to VC2)

I had to go back to VC1 and then tap the cell to VC2 again to let "passedValue" showing what it supposed to be there.

anyone know why is this happening ?

Answer

This might be due to call to Firebase that is async (not 100% sure). Also You are calling segue from storyboard so I would suggest following:

  • Remove segue from storyboard
  • in your response from Firebase, add following: self.performSegueWithIdentifier("ToVari", sender: self)

and you should be fine.