MacOS distributedNotification lost on background app Swift

255 Views Asked by At

I am trying to send a distributed notification to another app, app2 from the app that has focus, app1. The notification is not acted on until app2 gains focus. To fix it, I activate the other app, then send the notification. This can't be right. First, the other app retains focus, second, there is no point to a distributed notification if it is lost unless the other is active. Note this is a Mac App using AppKit, not an IOS app with UIKit

let yes = NSRunningApplication.runningApplications(withBundleIdentifier: "Lip.Balance20")
        
        if yes.count > 0 {
            yes[0].activate( )  // Shift focus to the Balance app  and send notification
            print ("***  App is running!")
            DistributedNotificationCenter.default.post(name: .checkAdded, object: nil,
                        userInfo: ["Application Name" : Bundle.main.bundleIdentifier!,
                                    "CheckToAdd":  r,
                                     "Account": a])
        }
1

There are 1 best solutions below

0
Anton Barkov On

When dealing with distributed notifications you should mind an option called SuspensionBehaviour.

As the deliverImmediately doc states:

The server delivers notifications matching this registration irrespective of whether suspended with an argument of true has been called.

You have to either specify to deliver notifications immediately (regardless of the receiving app's suspension status) when you send a notification (this is a slightly different method, note the last parameter):

DistributedNotificationCenter.default().postNotificationName(
    .checkAdded,
    object: nil,
    userInfo: [...],
    deliverImmediately: true
)

Or make sure that you specify it when subscribing to notifications:

DistributedNotificationCenter.default().addObserver(
    self,
    selector: ...,
    name: ...,
    object: nil,
    suspensionBehavior: .deliverImmediately
)