A lightweigth wrapper around Swift Foundation NotificationCenter, which doesn't require playing with stringly-typed API.
Example keyboard notifications
// Create a type safe notification class or struct which conforms to NotificationDescriptor
struct UserNotification: NotificationDescriptor {
let data: String
static var notificationName = Notification.Name(rawValue: "UserNotification")
}
// Subscribe to the notification
/// token is an opaque class which is used to unsubscribe from the notification. When the token gets deallocated, the observer is removed from NotificationCenter
let token = NotificationCenter.default.addObserver { (notification: UserNotification) in
// Use UserNotification
}
// Post this notification
NotificationCenter.default.post(notification: UserNotification(data: expectedData))
// That's it!
// Create a type safe notification class or struct which conforms to NotificationDescriptor
struct SystemNotification: NotificationDescriptor {
static var notificationName = Notification.Name(rawValue: "SystemNotification")
}
// Add conformance to ExpressibleByNotification
extension SystemNotification: ExpressibleByNotification {
init(_ notification: Notification) {
//
}
}
// Subscribe to this notification
/// token is an opaque class which is used to unsubscribe from the notification. When the token gets deallocated, the observer is removed from NotificationCenter
let token = NotificationCenter.default.addObserver { (notification: SystemNotification) in
// Use SystemNotification here
}
// That's it!
- Add CI for linux and iOS
- Add more tests
- Create a dependent repo which will have wrappers around system notifications
Special thanks to objc.io swift talk for the idea.