Swift 4.0 e Xcode 9.0+:
Invia notifica (posta):
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
O
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"])
Ricevi (ricevi) notifica:
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Gestore del metodo di funzione per la notifica ricevuta:
@objc func methodOfReceivedNotification(notification: Notification) {}
Swift 3.0 e Xcode 8.0+:
Invia notifica (posta):
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
Ricevi (ricevi) notifica:
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Gestore del metodo per la notifica ricevuta:
func methodOfReceivedNotification(notification: Notification) {
// Take Action on Notification
}
Rimuovi notifica:
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil)
}
Swift 2.3 e Xcode 7:
Invia notifica (posta)
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Ricevi (ricevi) notifica
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
Gestore del metodo per la notifica ricevuta
func methodOfReceivedNotification(notification: NSNotification){
// Take Action on Notification
}
Per le versioni storiche di Xcode ...
Invia notifica (posta)
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Ricevi (ricevi) notifica
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)
Rimuovi notifica
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed
Gestore del metodo per la notifica ricevuta
func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
Annota la classe o il metodo target con @objc
@objc private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
// Or
dynamic private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}