Skip to content

Instantly share code, notes, and snippets.

@ericdke
Created October 10, 2014 21:01
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save ericdke/fec20e6db9e0aa25e8ea to your computer and use it in GitHub Desktop.
Save ericdke/fec20e6db9e0aa25e8ea to your computer and use it in GitHub Desktop.
Deliver an OSX notification with Swift
func showNotification() -> Void {
var notification = NSUserNotification()
notification.title = "Test from Swift"
notification.informativeText = "The body of this Swift notification"
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}
//showNotification()
@ixeau
Copy link

ixeau commented Jan 5, 2017

Hey @nabtron, could you please explain why we have to conform the class to NSUserNotificationCenterDelegate? For me it work’s also without.

@eonist
Copy link

eonist commented Aug 13, 2017

@ixeau same here. Maybe The picture part?

@vetrek
Copy link

vetrek commented Oct 31, 2017

@ixeau Without NSUserNotificationCenterDelegate your notification will be shown only into the Notification center. If you want to have the popup and probably interact with your Notification you need NSUserNotificationCenterDelegate.
Example:

func showNotification() -> Void {
            let notification = NSUserNotification()
            notification.title = "Test."
            notification.subtitle = "Sub Test."
            notification.soundName = NSUserNotificationDefaultSoundName
            NSUserNotificationCenter.default.delegate = self
            NSUserNotificationCenter.default.deliver(notification)
}

func userNotificationCenter(_ center: NSUserNotificationCenter,
                                         shouldPresent notification: NSUserNotification) -> Bool {
        return true
}

This will show the top-right popup.

@gingerbeardman
Copy link

Thanks @Valerio69 that worked for me, I was missing NSUserNotificationCenter.default.delegate = self

@jsguru-git
Copy link

Thanks @Valerio69. Thank you so much, I could have an app that pops up notification upper-right of the screen.

@fhefh2015
Copy link

https://gist.github.com/code4you2021/cf184702b298181238aeb3fd781db203

UNUserNotificationCenter | Apple Developer Documentation
https://developer.apple.com/documentation/usernotifications/unusernotificationcenter

Availability
iOS 10.0+
iPadOS 10.0+
macOS 10.14+
Mac Catalyst 13.0+
tvOS 10.0+
watchOS 3.0+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment