-
Notifications
You must be signed in to change notification settings - Fork 3
iOS Notifications
Kevin Leong edited this page Oct 28, 2016
·
2 revisions
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBOutlet weak var label: UILabel!
let notificationMessage = "Notification Received"
let notificationKey = "com.example.someNotificationKey"
@IBAction func didTapButton(sender: UIButton) {
/*
On button tap, send a notification.
The broadcast is sent using a unique notification key, which
observers can listen on.
The `object` field allows observers to filter notifications,
so normally the notification sender is used as the object.
It is, however, up to the sender to populate this field with itself
or another relevant object or `nil`.
The user info dictionary allows data to be passed to any
observers.
`userInfo` is of type `[NSObject : AnyObject]`
*/
NSNotificationCenter
.defaultCenter()
.postNotificationName(
notificationKey,
object: button,
userInfo: ["message": notificationMessage]
)
}
override func viewDidLoad() {
/*
Subscribe to receive notifications on the `name` channel.
The `object` field allows for filtering, usually by sender.
`selector` is the method that should handle any relevant notifications.
*/
NSNotificationCenter
.defaultCenter()
.addObserver(
self,
selector: #selector(ViewController.displayNotificationMessage(_:)),
name: notificationKey,
object: button
)
super.viewDidLoad()
}
func displayNotificationMessage(notification: NSNotification) {
// Unwrap the notification message from the `userInfo` field within the
// notification object.
label.text = (notification.userInfo as! [String: String])["message"]
}
}
- Fundamentals of NSNotificationCenter in Swift - Andrew Bancroft
- NSNotificationCenter vs Delegation - Andrew Bancroft
deinit {
/*
Unsubscribe from all notifications to avoid attempted accesses
to deallocated objects.
*/
NSNotificationCenter.defaultCenter().removeObserver(self)
}