My type-safe Notifications with Blackjack and Hookers
⭐️ | Key Features |
---|---|
🐧 | Swift 4.0 |
🏰 | Strong typed |
🎭 | Extendable |
- Avoid string-based notification syntax 😡
- Avoid casting magic in notification handlers 🤢
func userNotificationCenter(center: NSUserNotificationCenter!, didActivateNotification notification: NSUserNotification!) {
let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
guard let type = userInfo["type"] as? String else {
print("It can't be :(")
}
if type == "LoggedIn" {
guard let accessToken = userInfo["accessToken"] as? String else {
print("It can't be :(")
}
}
}
Copy XNotificationCenter.swift to your project
You can add any properties you need.
public struct NewUserNotification: Notification {
public let userName: String
public init(userName: String) {
self.userName = userName
}
}
let notificationCenter = XNotificationCenter()
let listener = notificationCenter.subscribe(forNotification: NewUserNotification.self) { (notification) in
print("Hi, \(notification.userName)")
}
// Create an instance
let notification = NewUserNotification(userName: "Admin")
// And send it
notificationCenter.send(notification: notification)
notificationCenter.remove(listener: listener)
notificationCenter.removeListeners(ofNotification: NewUserNotification.self)
notificationCenter.removeAllListeners()