使用PyObjC与Mountain Lion的通知中心合作

时间:2012-08-30 18:12:32

标签: python osx-mountain-lion pyobjc nsusernotification

我正在尝试从我的python脚本向Mountain Lion发送通知,并对通知的点击做出反应。现在可以完美地发送通知。但是,我无法让Lion在点击后回拨我的剧本。

这是我的工作。我实现了一个Notification类。该类实例的唯一目的是通过调用notify()来提供通知。在同一方法中,我将对象设置为app的委托。

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_()。不幸的是,从未发生过我做错了什么?

1 个答案:

答案 0 :(得分:8)

好的,找到了。没有运行AppHelper.runEventLoop()。显然是一个facepalm的错误。以下代码有效:

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"]])