user3722523 user3722523 - 1 month ago 8
Swift Question

Pass data back, from a sheet to the ViewController

I want to pass the data from the Sheet back to the ViewController.

I tried with delegates but it don't works because when I close the sheet (self.dismiss(self)), the ViewController behind is not refreshed.

enter image description here

Answer

You will have to use a singleton class know as the NSNotificationCenter

Add this Statement before you call the method presentViewController in ViewController class

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.funcToBeExecuted(_:)), name:String, object: nil)

Add this Statement before dismissViewController in Sheet class

NSNotificationCenter.defaultCenter().postNotificationName(String, object: AnyObject?, userInfo: [NSObject : AnyObject]?))

So technically this is how it works. You set an observer in the application waiting to be posted by the application when to execute the #selector method. When the application executes the postNotification statement all observers in the memory having the NotificationName same as that of postNotification are triggered and implement their assigned #selectors.

userInfo in the postNotificationName in the parameter which helps to pass data from one place to another or even to multiple observers of the same name. So in the method to be executed by the NSNotification selector we can access the userInfo as stated below.

func funcToBeExecuted(notification: NSNotification)
{
    let receivedData = notification.userInfo
}

This should do the trick for you.