首页 > 解决方案 > Swift 通知已发送但未收到

问题描述

我添加了一个观察者,以便在连接充电器时收到通知。

CFNotificationCenterAddObserver(
  CFNotificationCenterGetDarwinNotifyCenter(),
  nil,
  { (_, _, _, _, _) in
    print("Sending...")
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test123"), object: nil)
  },
  kIOPSNotifyAttach as CFString?,
  nil, 
  .deliverImmediately
)

连接充电器后,会发送通知,以便我可以在我的应用程序中做出反应。所以我在我的应用程序中添加了一个观察者

NotificationCenter.default.addObserver(
  self,
  selector: #selector(reactToNotification(_:)),
  name: NSNotification.Name(rawValue: "test123"),
  object: nil)

通知已正确发送,但永远不会调用关联的函数。

@objc func reactToNotification(_ notification: Notification) {
    print("Receiving...")
}

我的概念中是否存在特定问题?

标签: swiftxcodecocoansnotificationcenternotificationcenter

解决方案


真的是不匹配的问题

  • 您发送了此通知NSNotification.Name(rawValue: "test123")
  • 但预计会得到这个:NSNotification.Name(rawValue: "test")

只是命名问题!


推荐阅读