Swift 4.0 & Xcode 9.0+:
Kirim (Posting) Pemberitahuan:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
ATAU
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"])
Terima (Dapatkan) Pemberitahuan:
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Penangan Fungsi-Metode untuk Pemberitahuan yang diterima:
@objc func methodOfReceivedNotification(notification: Notification) {}
Swift 3.0 & Xcode 8.0+:
Kirim (Posting) Pemberitahuan:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
Terima (Dapatkan) Pemberitahuan:
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
Penangan metode untuk Notifikasi yang diterima:
func methodOfReceivedNotification(notification: Notification) {
// Take Action on Notification
}
Hapus Pemberitahuan:
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil)
}
Swift 2.3 & Xcode 7:
Kirim (Posting) Pemberitahuan
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Terima (Dapatkan) Pemberitahuan
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
Penangan metode untuk Notifikasi yang diterima
func methodOfReceivedNotification(notification: NSNotification){
// Take Action on Notification
}
Untuk versi Xcode yang bersejarah ...
Kirim (Posting) Pemberitahuan
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
Terima (Dapatkan) Pemberitahuan
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)
Hapus Notifikasi
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed
Penangan metode untuk Notifikasi yang diterima
func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
Membubuhi keterangan kelas atau metode target dengan @objc
@objc private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
// Or
dynamic private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}