测试已测试 | ✓ |
Lang语言 | Obj-CObjective C |
许可 | MIT |
发布上次发布 | 2015年4月 |
由 Claus Höfele 维护。
使用 Darwin 通知中心进行带有可寻址接收器的进程间信号。
查看 版本 以获取最新更新的概览。
此仓库中的示例包含一个 iPhone 应用、一个 Today 小工具和一个 WatchKit 扩展,它们通过使用 CCHDarwinNotificationCenter
交换信号。要查看更新,至少启动两个进程,如 WatchKit 应用和 iPhone 应用。
需要与人沟通? 我在 Twitter 上是 @claushoefele。
使用 CocoaPods 将 CCHDarwinNotificationCenter
集成到您的项目中。最小部署目标是 iOS 的 7.0 和 OS X 的 10.9。
platform :ios, '7.0'
pod "CCHDarwinNotificationCenter"
platform :osx, '10.9'
pod "CCHDarwinNotificationCenter"
Darwin 通知中心 是 iOS 和 OS X 中的一个系统机制,可以在进程之间发送信号。当需要交换 iPhone 应用通知 WatchKit 扩展有新数据到来等两个或多个运行的进程之间的信息时,它很有用。
Darwin 通知仅是一个信号;除了通知标识符之外,它不能传输任何数据。如果您需要在进程之间共享数据,可以设置一个 应用组,这允许您通过 NSUserDefaults
和 Core Data 等API交换数据。
Darwin 通知无需应用组或其他设置即可工作。因为通知命名空间是在系统中的所有应用之间共享的,苹果推荐使用回推-DNS 风格的命名,例如 "com.example.MyMessage"。
CCHDarwinNotificationCenter
通过以下方式简化 Darwin 通知的处理
NSNotification
通知要发送 Darwin 通知使用
CCHDarwinNotificationCenter.postNotificationWithIdentifier("com.example.MyMessage")
要接收 Darwin 通知,首先将它们转换为 NSNotification
CCHDarwinNotificationCenter.startForwardingDarwinNotificationsWithIdentifier("com.example.MyMessage")
然后通过 NSNotificationCenter
API 接收转换后的信号
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationDidReceive", name:"com.example.MyMessage", object: nil)
func notificationDidReceive() {
println("notificationDidReceive")
}
达尔文通知的一个缺点是发送者自身也会接收到它们。如果您有一个iPhone应用程序、一个今日widget和一个WatchKit扩展,用相同的标识符发送通知将很难判断信号是从哪里来的。
因此,CCHDarwinNotificationCenter
提供了一个API,该API将特定于进程的字符串附加到通知标识符。然后使用这个后缀来过滤掉您不需要的消息。API如下所示
CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier("com.example.MyMessage", fromEndpoints: .Default)
CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier("com.example.MyMessage", fromEndpoints: .Default)
CCHDarwinNotificationCenter.postNotificationWithIdentifier("com.example.MyMessage")
请注意,这个API的方法中不包含“Darwin”这个词。端点掩码允许您过滤消息,其中.Default
代表除您自己进程发送的消息外的所有消息。