Swift & NSUserNotification - No banner or alert, but is silently added to the notification list
Asked Answered
K

1

12

I am learning Swift and wanted to display a simple user notification as a test.
My build is successful, but no banner is shown, instead, the notification is silently added to the list of notifications. I have verified 'Do Not Disturb' is off, I tried the same in AppleScript, successfully and once when fiddling around with NSUserNotificationAlertStyle and the code in the info.plist of my application, I got a successful, non-silent alert (not a banner).
However, this only happened once.

I have created a new project, with Swift files and without storyboards. My AppDelegate.swift contains

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        var notification:NSUserNotification = NSUserNotification()
        notification.title = "Title"
        notification.subtitle = "Subtitle"
        notification.informativeText = "Informative text"

        notification.soundName = NSUserNotificationDefaultSoundName

        notification.deliveryDate = NSDate(timeIntervalSinceNow: 5)
        var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
        if let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() {
            notificationcenter.scheduleNotification(notification)
        }
    }

    func applicationWillTerminate(aNotification: NSNotification?) {
        // Insert code here to tear down your application
    }


}

And my info.plist does not contain the NSUserNotificationAlertStyle mentioned earlier, for this shouldn't be necessary for banners, I believe.

Lastly, yes, application "test" (for that's what I've named it) is set to show banners, as such. screenshot of Notifications System Panel
Summarised: My application successfully makes notifications, and these will be added to the list of notifications, but not shown as a banner. (I am using OS X Yosemite 10.10. I hope this issue has nothing to do with the beta)

Kalagher answered 14/8, 2014 at 8:15 Comment(0)
B
23

Some notifications are not shown if the application is the foreground/active application at the time the notification is delivered. See NSUserNotification's presented property for more info.

For example, when you are in iTunes and a new song starts playing, you already see which song is playing and there's no need for a banner to be shown.

Note that you can still get notified when a notification is delivered (and check presented) by providing a delegate to NSUserNotificationCenter, including overriding the presentation behavior by implementing userNotificationCenter:shouldPresentNotification:.

Blennioid answered 14/8, 2014 at 8:45 Comment(1)
Yup, I hadn't seen this! Very helpful!Kalagher

© 2022 - 2024 — McMap. All rights reserved.