使用PyObjC山狮的通知中心工作(Working with Mountain Lion's

2019-06-27 14:09发布

我想从我的python脚本将通知发送到山狮和应对点击通知。 发送通知工作完全由现在发现。 但我还是没能拿到金狮在点击呼叫回我的脚本。

这是我做的。 我实现了一个通知类。 这个类的一个实例的唯一目的是通过调用能够提供通知notify() 在同样的方法我设置的对象的应用程序的委托。

import Foundation
import objc
import AppKit

class MountainLionNotification(Foundation.NSObject, Notification):

    def notify(self, title, subtitle, text, url):
        NSUserNotification = objc.lookUpClass('NSUserNotification')
        NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(str(title))
        notification.setSubtitle_(str(subtitle))
        notification.setInformativeText_(str(text))
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
        notification.setUserInfo_({"action":"open_url", "value":url})
        AppKit.NSApplication.sharedApplication().setDelegate_(self)
        NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

    def applicationDidFinishLaunching_(self, sender):
        userInfo = sender.userInfo()
        if userInfo["action"] == "open_url":
            import subprocess
            subprocess.Popen(['open', userInfo["value"]])

现在,我希望applicationDidFinishLaunching_()要在对通知的点击调用。 不幸的从未发生过。 我究竟做错了什么?

Answer 1:

好了,找到了。 没跑AppHelper.runEventLoop() 显然,一个捂脸错误。 下面的代码工作:

class MountainLionNotification(Foundation.NSObject, Notification):

    def notify(self, title, subtitle, text, url):
        NSUserNotification = objc.lookUpClass('NSUserNotification')
        NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(str(title))
        notification.setSubtitle_(str(subtitle))
        notification.setInformativeText_(str(text))
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
        notification.setHasActionButton_(True)
        notification.setOtherButtonTitle_("View")
        notification.setUserInfo_({"action":"open_url", "value":url})
        NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
        NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

    def userNotificationCenter_didActivateNotification_(self, center, notification):
        userInfo = notification.userInfo()
        if userInfo["action"] == "open_url":
            import subprocess
            subprocess.Popen(['open', userInfo["value"]])


文章来源: Working with Mountain Lion's Notification Center using PyObjC