使用PyObjC与Mountain Lion的通知中心一起使用

发布于 2021-01-29 15:25:15

我正尝试从我的python脚本向Mountain
Lion发送通知,并对点击通知做出反应。到目前为止,发送通知的工作非常完美。但是,我仍然无法让Lion单击一次来回叫我的脚本。

这是我的工作。我实现了一个Notification类。该类实例的唯一目的是通过调用提供通知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_()在单击通知时会被调用。不幸的是,这永远不会发生。我究竟做错了什么?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看