Search code examples
cocoainputosx-mavericksnsusernotificationcenter

Create notification with reply field


How do i get input from a notification with a reply field. I have not found anything in the documentation

Here is my current code, what do I need to get a response from the user?

#import "AppDelegate.h"

@implementation AppDelegate
@synthesize nTitle;
@synthesize nMessage;

- (IBAction)showNotification:(id)sender{
    NSUserNotification *notification = [[NSUserNotification alloc] init];
    notification.title = [nTitle stringValue];
    notification.informativeText = [nMessage stringValue];
    notification.soundName = NSUserNotificationDefaultSoundName;

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
    return YES;
}

@end

Where can i find more recent information and documentation for the notification center?


Solution

  • You can find the latest documentation in headers as usual. First of all, make sure you are using OSX SDK 10.9. There are few new fields with description.

    NSUserNotification.h:
    
    // Set to YES if the notification has a reply button. The default value is NO.
    // If both this and hasActionButton are YES, the reply button will be shown.
    @property BOOL hasReplyButton NS_AVAILABLE(10_9, NA);
    
    // Optional placeholder for inline reply field.
    @property (copy) NSString *responsePlaceholder NS_AVAILABLE(10_9, NA);
    
    // When a notification has been responded to, the NSUserNotificationCenter delegate
    // didActivateNotification: will be called with the notification with the activationType
    // set to NSUserNotificationActivationTypeReplied and the response set on the response property
    @property (readonly) NSAttributedString *response NS_AVAILABLE(10_9, NA);
    

    Let's do it:

    - (IBAction)showNotification:(id)sender{
    NSUserNotification *notification = [[NSUserNotification alloc] init];
    ...
    notification.responsePlaceholder = @"Reply";
    notification.hasReplyButton = true;
    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
    }
    
    - (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
    {
        if (notification.activationType == NSUserNotificationActivationTypeReplied){
            NSString* userResponse = notification.response.string;
        }
    }
    

    Notice that the reply button is hidden until mouse is outside a notification window and the reply field will be shown after button click.