Swift 4.0 y Xcode 9.0+:
Enviar (publicar) notificación:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
O
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"])
Recibir (Obtener) Notificación:
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Manejador de métodos y funciones para notificaciones recibidas:
@objc func methodOfReceivedNotification(notification: Notification) {}
Swift 3.0 y Xcode 8.0+:
Enviar (publicar) notificación:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
Recibir (Obtener) Notificación:
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Manejador de métodos para notificaciones recibidas:
func methodOfReceivedNotification(notification: Notification) {
// Take Action on Notification
}
Eliminar notificación:
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil)
}
Swift 2.3 y Xcode 7:
Enviar (publicar) notificación
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Recibir (Obtener) Notificación
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
Manejador de métodos para notificaciones recibidas
func methodOfReceivedNotification(notification: NSNotification){
// Take Action on Notification
}
Para versiones históricas de Xcode ...
Enviar (publicar) notificación
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Recibir (Obtener) Notificación
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)
Eliminar notificación
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed
Manejador de métodos para notificaciones recibidas
func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
Anote la clase o el método de destino con @objc
@objc private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
// Or
dynamic private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}