TypedNotifications
NotificationCenter
周围的一个包装器,用于在iOS应用中跨发送带有负载的类型通知。
🙁 ) 翻转成快乐的表情 (🙃 ).
异步行为很难。让我们让它变得简单一些,这样我们就可以把那个悲伤的表情 (使用TypedNotifications非常简单。您可以在几分钟内将其添加到您的应用中,并替换所有未类型化的 Notification
。
注册通知
您可以为包含通知的负载或无负载通知注册通知。
func register<T: TypedNotification>(type: T.Type, observer: Any, object: Any? = nil, selector: Selector)
func register<T: TypedPayloadNotification>(type: T.Type, observer: Any, object: Any? = nil, selector: Selector)
发送通知
您可以发送包含通知的数据负载,或者不包含数据负载的通知。
func post<T: TypedNotification>(typedNotification: T, object: Any? = nil)
func post<T: TypedPayloadNotification>(typedNotification: T, object: Any? = nil)
从通知中提取值
只有包含通知的数据负载可以提取其数据负载,因为……
func getPayload<T: TypedPayloadNotification>(notificationType: T.Type) -> T.Payload?
看到这些T
字符可能会有点吓人,但让我们通过一些示例来分解它,看看这有多简单。
示例
创建一些您希望通过应用程序发送的值。
enum Job {
case softwareDeveloper
case designer
case conArtist
}
struct Person {
let name: String
let job: Job
}
创建发送值的公告
如果您没有数据负载,只想发送一条消息,则可以使用TypedNotification
,如下所示。
struct SomeEventNotification: TypedNotification {}
在我们的示例中,我们使用带有数据负载的TypedPayloadNotification
。
struct TypedPersonNotification: TypedPayloadNotification {
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)")
}
就是这样!你现在已经在你的应用中发送了文本通知。
如果你想要玩专家模式,我建议使用泛型和通过这种方式将通知传递到你的应用中。
struct GenericTypedPayloadNotification<T>: TypedPayloadNotification {
let payload: T
}
需求
- iOS 8.0+
- Xcode 7.3+
安装
你可以使用 CocoaPods 通过将其添加到你的 Podfile
中来安装 TypedNotifications
。
platform :ios, '8.0'
use_frameworks!
pod 'TypedNotifications'
或者通过下载 TypedNotifications.swift
并将其拖放到你的项目中手动安装。
关于我
嗨,我在网络上的任何地方都是 Joe,尤其是在 Twitter。
许可
查看许可了解如何使用TypedNotifications。