简体   繁体   中英

Have main app open with NSUserNotification posted from helper

I have a helper application that is active when the GUI app is not. The helper application is posting notifications to [NSUserNotificationCenter defaultNotificationCenter]. I'd like to have the GUI app open when the user activates a notification from the helper. Is there a way to do this?

I'd also prefer that the helper app post notifications with the same name as the main app, but that's less of an issue than getting the didActivateNotification: sent to the right executable.

You could simply open your main app via NSWorkspace in the didActivateNotification: delegate method:

- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
    [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:@"/Applications/TextEdit.app"] options:0 configuration:nil error:nil];
}

This will open the app at the specified URL if it is not running, or bring it to the foreground if it is already open.

An alternative approach would be to register a custom URL scheme in your main app, and use NSWorkspace's openURL. This way you could define a simple action/parameter grammar that triggers different behaviour in your main app.

Posting notifications works only with running apps, that have registered for receiving these notifications.

If you want to launch your GUI app, you can use [ [ NSWorkspace sharedWorkSpace] launchApplication: pathToApplication]; pathToApplication should be set correct and complete, eg /applications/the GUIapp

The method must be implemented in your helper app, so reaction to the user activation has to be implemented there also.

I assume that you have set the Delegate for the NSUserNoticationCenter, so userNotificationCenter:didActivateNotification: is received. The discussion part of this link https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUserNotificationCenterDelegate_Protocol/Reference/Reference.html#jumpTo_3 explains, how to receive and extract the information from an "userInfo" dict, which you can feed with the information, which app shall react, see this link for the userInfo https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUserNotification_Class/Reference/Reference.html#jumpTo_17

I haven't used NSUserNotifications but maybe this helps also NSUserNotificationCenter dismiss notification .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM