cocoansalert

How to create alerts that look similar to OS X notifications?


From alerts, I'm assuming this picture represents is a panel, not a sheet (my understanding is that sheets are overlays over already open apps).

I'm looking to create a custom, or just built in 'clean' popup alert (notification). I can't seem to find anything within NSAlert that speaks of customizing the alert - alertType seems like it might but apparently it is for conveying importance.

An example is something like this:

enter image description here

(source: https://i.sstatic.net/WJhV8.jpg)


Solution

  • The NSUserNotificationCenter class is used to present these "user notifications" in the upper-right of the screen:

    notification example

    import AppKit
    
    let note = NSUserNotification()
    note.title = "Hi Stack Overflow"
    note.subtitle = "How’s it going?"
    note.contentImage = NSImage(contentsOfURL: NSURL(string: "http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png")!)
    
    NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(note)
    

    (The one you see from Gmail is a custom non-standard notification system that Chrome provides. You can probably take advantage of that if you write a Chrome extension, but NSUserNotificationCenter is more normal.)