cvrattos
cvrattos

Reputation: 51

prepareForSegue called before performSegue

I am trying to perform a segue that passes a number of variables to the next view including one variable, currentID, which is retrieved from a parse database. performSegue should not be called until after currentID has been set to the currentID downloaded from the database. However, when I run the code, currentID ends up being an empty string when it is passed to the next view.

Here is my code called by the Button:

@IBAction func submitButtonPressed(_ sender: Any) {

    let point = PFGeoPoint(latitude:0.0, longitude:0.0)
    let testObject = PFObject(className: "Person")

    testObject["inputAmount"] = inputAmount
    testObject["outputAmount"] = outputAmount
    testObject["inputCurrency"] = inputCurrency
    testObject["outputCurrency"] = outputCurrency
    testObject["location"] = point

    testObject.saveInBackground { (success, error) -> Void in

        // added test for success 11th July 2016

        if success {
            print("Object has been saved.")

            self.currentID = String(describing: testObject.objectId!)
            if(self.currentID != ""){
                self.performSegue(withIdentifier: "mainToListSegue", sender: self)
            }

        } else {
            if error != nil {
                print (error)
            } else {
                print ("Error")
            }
        }
    }
}

And here is the prepareForSegue method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let listViewController = (segue.destination as! UINavigationController).viewControllers[0] as! ListViewController
    listViewController.inputCurrency = inputCurrency
    listViewController.outputCurrency = outputCurrency
    listViewController.inputAmount = inputAmount
    listViewController.outputAmount = outputAmount
    listViewController.currentID = currentID
    listViewController.cellContent = cellContent
}

Upvotes: 0

Views: 795

Answers (2)

GIJOW
GIJOW

Reputation: 2343

To achieve your needs, you MUST connect your segue between viewcontrollers, and not from UIButton to viewcontroller.

Every time you need to prepare your segue before calling it, this is the procedure:

enter image description here

Then, name it and use delegate method

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" {

    }
}

Upvotes: 3

Prashant Humney
Prashant Humney

Reputation: 143

For navigating from one controller to another, connect your segue from view controller instead of from the button and it will work.

Upvotes: 1

Related Questions