Search code examples
macostimemachine

Event notifications in macOS


Is it possible for a macOS application to listen for specific events originating from another application?

I'd like to detect when Time Machine backups are initiated, in order to create point-in-time snapshots of the NAS folder where the sparsebundle is located.


Solution

  • The Time Machine engine sends distributed notifications.

    Add an observer

    Objective-C

    [[NSDistributedNotificationCenter defaultCenter] addObserver:self
                                                       selector:@selector(handleNotifications:)
                                                           name:nil
                                                         object:nil];
    

    Swift

    DistributedNotificationCenter.default().addObserver(self, selector: #selector(handleNotifications), name: nil, object: nil)
    

    and implement the corresponding selector

    Objective-C

    - (void)handleNotifications:(NSNotification *)notification {
        NSLog(@"%@", notification);
    }
    

    Swift

    @objc func handleNotifications(_ notification : Notification) {
        print(notification)
    }
    

    You have to filter the notifications related to Time Machine. You can also observe specific notifications via the name parameter