Skip to content

Instantly share code, notes, and snippets.

@chenr2
Last active August 29, 2015 14:25
Show Gist options
  • Save chenr2/4084de72942e0d01117c to your computer and use it in GitHub Desktop.
Save chenr2/4084de72942e0d01117c to your computer and use it in GitHub Desktop.
Swift: NSNotification basics

NSNotification basics

This is how you fire an event:

NSNotificationCenter.defaultCenter().postNotificationName("doSomething", object: nil)

Elsewhere, listen for the event like so:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "doSomething", name: "doSomething", object: nil)

Don't forget to cleanup after yourself:

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

Passing data

If you want to pass data, you need to send an userInfo object:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    NSNotificationCenter.defaultCenter().postNotificationName("doSomethingWithPayload", object: nil, userInfo: userInfo)
}

Then add a colon to your selector because you're passing a parameter:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "doSomethingWithPayload:", name: "doSomething", object: nil)

Now you need to unwrap the NSNotification object to get to the userInfo chewy center:

func doSomethingWithPayload(notification: NSNotification){ 
    if let payload = notification.userInfo {

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment