kol*_*man 8 python pyobjc osx-mountain-lion 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"]])
Run Code Online (Sandbox Code Playgroud)
现在我希望applicationDidFinishLaunching_()在点击通知时被调用.不幸的是,从未发生过 我究竟做错了什么?
好的,找到了.没跑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"]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3889 次 |
| 最近记录: |