gpt4 book ai didi

python - 使用 PyObjC 处理 Mountain Lion 的通知中心

转载 作者:太空狗 更新时间:2023-10-29 20:59:17 24 4
gpt4 key购买 nike

我正在尝试从我的 python 脚本向 Mountain Lion 发送通知并对通知的点击使用react。发送通知现在可以完美地找到。但是我无法让 Lion 在单击时回调我的脚本。

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

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_()。不幸的是,这永远不会发生。我做错了什么?

最佳答案

好的,找到了。没有运行 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"]])

关于python - 使用 PyObjC 处理 Mountain Lion 的通知中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com