A wrapper around NotificationCenter
for sending typed notifications with payloads across your iOS app.
Asynchronous behavior is hard. Let's make it a little easier so we can turn that frown (🙁) upside down (🙃).
Using TypedNotifications is easy. You can drop it into your app and replace all of your un-typed Notification
s in minutes.
func register<T>(type: T.Type, observer: Any, selector: Selector) where T: TypedNotification
func post<T>(typedNotification: T) where T: TypedNotification
func getPayload<T>(notificationType: T.Type) -> T.Payload? where T: TypedNotification
Now that might look a little scary at first with all those T
s, but let's break it down with some examples and show you how easy this is.
enum Job {
case softwareDeveloper
case designer
case conArtist
}
struct Person {
let name: String
let job: Job
}
struct TypedPersonNotification: TypedNotification {
let payload: Person
}
NotificationCenter.default.register(type: TypedPersonNotification.self, observer: self, selector: #selector(personNotificationWasReceived))
let amanda = Person(name: "Amanda", job: .softwareDeveloper)
let amandaNotification = TypedPersonNotification(payload: amanda)
NotificationCenter.default.post(typedNotification: amandaNotification)
@objc func personNotificationWasReceived(notification: Notification) {
guard let person = notification.getPayload(notificationType: TypedPersonNotification.self) else {
os_log("Could not properly retrieve payload from TypedPersonNotification")
return
}
let nameText = "Name: \(person.name)"
let jobText = "Job: \(person.job.title)"
print("Got our Person payload!\n\(nameText)\n\(jobText)")
}
If you want to play on expert mode, I recommend using generics and passing notifications through your app that way.
struct GenericTypedNotification<T>: TypedNotification {
let payload: T
}
- iOS 8.0+
- Xcode 7.3+
You can use CocoaPods to install TypedNotifications
by adding it to your Podfile
:
platform :ios, '8.0'
use_frameworks!
pod 'TypedNotifications'
Or install it manually by downloading TypedNotifications.swift
and dropping it in your project.
Hi, I'm Joe everywhere on the web, but especially on Twitter.
See the license for more information about how you can use TypedNotifications.