Search code examples
swiftparse-platform

Data from parse is not being passed through prepareForSegue


I want to get the objectId from parse and pass it through segue. But the objectId is passing over as an empty string:

class QueryViewController: UIViewController {

var objectIdFormParse = String()

@IBAction func makeQueryButtonTapped(_ sender: UIButton) {

makeSearchObject.saveInBackground { (success, error) in
        if error == nil {
            if let getObjectId = makeSearchObject.objectId {
             self.objectIdFormParse = getObjectId
                print("objectId in queryVC: \(self.objectIdForomParse)")
            }
            //Successfully saved
        } else {
            //Error, check error
        }
    }
    performSegue(withIdentifier: resultsSegue, sender: self)
}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == resultsSegue
        {
            let destination = segue.destination as! ResultsViewController

            destination.objectIdFromQueryVC = objectIdForomParse
        }
    }
}

The print statement prints the objectId correctly, but the segue passes empty.


Solution

  • You can pass the data through perform segue. just change perform segue line with following one:

    performSegue(withIdentifier: resultsSegue, sender: objectIdForomParse)
    

    And in your prepare for segue method add following lines:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.identifier == resultsSegue
            {
                let destination = segue.destination as! ResultsViewController
                let objectIDParse = sender as! String
                destination.objectIdFromQueryVC = objectIDParse
            }
        }
    }
    

    Perform segue when your error is nil since you are setting objectIdForomParse only when your error is nil.

    Update :

    @IBAction func makeQueryButtonTapped(_ sender: UIButton) {
    
    makeSearchObject.saveInBackground { (success, error) in
            if error == nil {
                if let getObjectId = makeSearchObject.objectId {
                 self.objectIdFormParse = getObjectId
                    print("objectId in queryVC: \(self.objectIdForomParse)")
            performSegue(withIdentifier: resultsSegue, sender: self)
                }
                //Successfully saved
            } else {
                //Error, check error
            }
        }
    
    }
    
     override func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.identifier == resultsSegue
            {
                let destination = segue.destination as! ResultsViewController
    
                destination.objectIdFromQueryVC = objectIdForomParse
            }
        }
    }