Search code examples
swiftxcodecocoansnotificationcenternotificationcenter

Swift Notification is sent but not received


I added an observer to be notified when a charger is connected.

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

When the charger is connected the a notification is sent so that I can react in my application. So I added an observer in my app

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

The notification is sent correctly but the associated function is never called.

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

Is there a specific problem in my concept?


Solution

  • It's really mismatch issue

    • You sent this notification NSNotification.Name(rawValue: "test123")
    • But expected to get this: NSNotification.Name(rawValue: "test")

    It's just naming issue!