Notifications in iOS

Posting a Notification

  1. First, create a global key before the class definition of the class that is posting the notification
  2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *