Posting a Notification
- First, create a global key before the class definition of the class that is posting the notification
- Post the notification
// Step 1 let HasLoggedInNotificationKey = "com.morgandavison.hasLoggedInNotificationKey" class MyClass { var userID: Int? func doSomething() { if let userID = userID { // Do stuff } else { login() } } private func login() { // User logs in // Step 2: Send notification NSNotificationCenter.defaultCenter().postNotificationName(HasLoggedInNotificationKey, object: self) } }
Listening for a Notification
3. Next, create an observer in the class where you are listening for the notification
4. Implement the selector method
class MyOtherClass { init() { // Step 3 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyOtherClasshHasLoggedIn(_:)), name: HasLoggedInNotificationKey, object: nil)) } // Notification Handling // Step 4 @objc func hasLoggedIn(notification: NSNotification) { // Do stuff } }
Remove Observer
5. Remove the observer
class MyOtherClass { init() { // Step 3 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyOtherClasshHasLoggedIn(_:)), name: HasLoggedInNotificationKey, object: nil)) } deinit { // Step 5 NSNotificationCenter.defaultCenter().removeObserver(self) } // Notification Handling // Step 4 @objc func hasLoggedIn(notification: NSNotification) { // Do stuff } }
If you selector is not being called, make sure your observer is set upĀ before the notification is posted.