macOS: system-wide notifications- 1 min
A straightforward yet pretty useful inter-process communication utility.
What are system-wide notifications?
Apple’s documentation says:
These routines allow processes to exchange stateless notification events. Processes post notifications to a single system-wide notification server, which then distributes notifications to client processes that have registered to receive those notifications, including processes run by other users.
In short, they give us the possibility to communicate between different processes. Brett Terpstra wrote a nice tutorial about how to use system-wide notifications with Terminal. How can we use them in Objective-C programs?
Let’s start with creating new Objective-C command line tool in Xcode.
Next, we need to import
notify.h into the
And finally, post notification.
notify.h is written in C, and that’s perfect because Objective-C is a superset of C.
To receive notification in a different process we need to register monitoring for this notification. Let’s open Terminal and type:
-1 means we are waiting for only one notification. After running our Objective-C command line program, we should receive the notification in Terminal.
Pretty cool. Now, let’s register a new notification using Objective-C.
I believe the code is self-explanatory. We are using
[[NSRunLoop currentRunLoop] run] to keep our program running. When a notification is received, the Xcode console will log our
notification received information. To post the notification from Terminal just type:
That’s all for now folks. Thanks for reading!