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 code!

Let’s start with creating new Objective-C command line tool in Xcode.
Next, we need to import notify.h into the main.m file.

#import "notify.h"

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:

notifyutil -1 com.aleksanderpopko.notify.first-notification && echo "notification received"

-1 means we are waiting for only one notification. After running our Objective-C command line program, we should receive the notification in Terminal.

notification received

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:

notifyutil -p com.aleksanderpopko.notify.second-notification

That’s all for now folks. Thanks for reading!

Aleksander Popko

Aleksander Popko

iOS & macOS Software Engineer

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora