user172902 user172902 - 11 months ago 43
iOS Question

Pass data to VC that is not the previous VC

When I go from VC1 to VC2, if VC2 gets dismissed, I could easily pass data back to VC1 by setting protocal in VC2 and have VC1 conform to it. I want to do something similar, however, with the following difference

When I go from VC1-> NavVC->VC2-> VC3. When VC3 gets dismissed, VC1 is shown. I want to be able to pass data back to VC1 and initiate some function in VC1. For example, I have an image to upload in VC3. As soon as VC3 gets dismissed, I am hoping to have a function in VC1 such as the following function where the image was the data from VC3

func uploadInitiate(image: UIImage) {}

Relationship of the three VC

VC1 is normal VC. It presents VC2 via

let navController = UINavigationController.init(rootViewController: VC2)
self.navigationController?.presentViewController(navController, animated: true, completion: nil)

VC2 is a custom FusumaCamera photo picker from cocoapods.
Once image is selected, I go to VC3 with the selected Image via

self.navigationController!.pushViewController(postVC, animated: true)

At VC3, I allow the user to interact with the image and make comments and press a button to upload to the server. I thought it would be nice to dismiss the VC straight away after button press and allow VC1 to initiate the upload with the data the came from VC3 (That way I can have a progress bar under navigation bar or display any warnings there)

Answer Source

You have multiple patterns that you can apply in similar situations. i will go with the delegation (recomended) example. Imagine you have VC1-> that presents modally a UINavigationController as a root controller and from there VC2 pushes VC3 to the stack. You have to define multiple protocols that will be called on the way you dismiss the VC3

protocol DismissVCDelegate : class {
    func dismissViewAndStartUpload(shouldUpload: Bool)

Then store the property:

weak var delegate: DismissVCDelegate!

Set the delegate when to the VC3 when you push it from VC2 and conform the the protocol you defined in VC2. Apply the same pattern all the way back to VC1 where you have passed multiple times the protocol back and you can start you upload task and you should dismiss the modally presented navigation controller like that:

func dismissViewAndStartUpload(shouldUpload: Bool) {
     self.presentedViewController.dismissViewControllerAnimated(true, completion: nil)}