I’m getting into Swift and need some help overcoming issues with an app which uses NotificationCenter observers and the Accessibility API. I’m running macOS 14.4.1 Sonoma. This is my first proper start-from-scratch Swift project, so any help would be very welcome 🙂
What I’m trying to do
I’m making a macOS app called ‘TidyDaemon’ which manipulates the size and position of windows for specified applications (such as Spotify and Mail). This will ensure that all of the windows for the specified applications are the same size and aligned to the screen, which is super helpful for OCD.
It’s important to note that the TidyDaemon is resizing the windows for other applications, not its own window (it doesn’t have a UI). This is why I am using the Accessibility API.
I’m trying to use the NotificationCenter to add observers for application launch notifications, so that the app window is resized and aligned when the app launches, and then you can move the windows around safe in the knowledge that the window positions will be reset next time the app launches. This means that the ‘TidyDaemon’ is constantly running in the background, so I’m trying to keep it as lightweight as possible.
A public GitHub repo for the project can be found here: https://github.com/AmeliaFD/TidyDaemon
What are the issues?
I’ve added several print statements to help with debugging. When I run the app using Xcode, I get the following console output. As you can see, I had Mail, Safari and Xcode open at the time, which is why they have process IDs. Pycharm, Maps, and Spotify weren’t open, which is why they don’t have process IDs.
Adding observer for com.jetbrains.pycharm
Adding observer for com.apple.Maps
Adding observer for com.apple.mail
pid: 28146
got element
created observer for 28146
Adding observer for com.apple.dt.Xcode
pid: 20555
got element
created observer for 20555
Adding observer for com.spotify.client
Adding observer for com.apple.Safari
pid: 27707
got element
created observer for 27707
However, when opening a new app (e.g. closing and reopening Safari) several things don’t happen:
-
The newly opened window is not the correct size or position. This suggests that there is an issue with the setLayout function.
-
Nothing is printed to the console. This suggests that the addObserver function was not called, implying that the observer for
didLaunchApplicationNotification
is not working as planned.
To address the obvious potential issues, yes I have granted TidyDaemon permission in System Settings > Privacy and Security > Accessibility. I have also set Application is Agent (UIElement)
to Yes
in Xcode.
How you can help
Please feel free to fork the repo to experiment with the code yourself. I would be very grateful if you can suggest fixes for the issues I’m encountering. Thanks in advance!