Skip to content

A wrapper around swift Foundation NotificationCenter, which doesn't require playing with stringly-typed API.

License

Notifications You must be signed in to change notification settings

S2Ler/ModernNotificationCenter

Repository files navigation

ModernNotificationCenter

Swift SPM Ready Carthage-compatible Build Status codebeat badge

A lightweigth wrapper around Swift Foundation NotificationCenter, which doesn't require playing with stringly-typed API.

Usage

Example keyboard notifications

Custom 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!

Working with system notifications or notifications you don't control

// 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!

TODO

  • Add CI for linux and iOS
  • Add more tests
  • Create a dependent repo which will have wrappers around system notifications

Credits

Special thanks to objc.io swift talk for the idea.

About

A wrapper around swift Foundation NotificationCenter, which doesn't require playing with stringly-typed API.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published