1

アプリが最前面にあるときにユーザー通知を表示したい。以下のコードを見つけましたが、デリゲートの使用方法がわかりません。ブール値を返すだけのようです。

class MyNotificationDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

func applicationDidFinishLaunching(aNotification: NSNotification) {
    NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
}

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

私は次のようないくつかの文を試しました:

var delegate : MyNotificationDelegate = MyNotificationDelegate()
var notification:NSUserNotification = NSUserNotification()
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()

delegate.userNotificationCenter(notificationcenter, shouldPresentNotification: notification)

ただし、バナーは表示されません。NSUserNotificationCenterの場合、deliverNotification:メソッドはバナーを表示する方法であることを知っています。NSUserNotificationCenterDelegateしかし、プロトコルについてはよくわかりません。

通知バナーを常に表示するにはどうすればよいですか?

4

1 に答える 1

2

通知センターのデリゲートとデリゲート メソッドを AppDelegate に実装する必要があります。他のクラスで実装すると、通知パネルに静かに表示されますが、バナーとして表示されません。

私は以下のように試しましたが、その動作は次のとおりです。

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {



    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let notification: MyNotificationDelegate = MyNotificationDelegate()
        NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
        notification.setNotification("Hi", message: "How are you?")
    }

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

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


}

class MyNotificationDelegate: NSObject {

    func setNotification(title: String, message: String)
    {
        let notification: NSUserNotification = NSUserNotification()
        notification.title = title
        notification.informativeText = message
        NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
    }
}
于 2015-10-21T06:05:30.287 に答える