-
-
Save ericdke/fec20e6db9e0aa25e8ea to your computer and use it in GitHub Desktop.
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() |
We also need to conform our class to NSUserNotificationCenterDelegate.
Check the detailed tutorial here for swift 3.0.1: https://nabtron.com/show-notification-cocoa-xcode-swift/
Hey @nabtron, could you please explain why we have to conform the class to NSUserNotificationCenterDelegate? For me it work’s also without.
@ixeau same here. Maybe The picture part?
@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.
Thanks @Valerio69 that worked for me, I was missing NSUserNotificationCenter.default.delegate = self
Thanks @Valerio69. Thank you so much, I could have an app that pops up notification upper-right of the screen.
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+
Note the new API for swift > 3, updated in my fork:
NSUserNotificationCenter.default.deliver(notification)