2013-04-09 3 views
0

Я не уверен, что у меня что-то не так, но из примеров, которые я смог найти. Я написал этот маленький мир.NSUserNotificationCenter не показывает уведомлений

#import <Foundation/Foundation.h> 
#import <Foundation/NSUserNotification.h> 


int main (int argc, const char * argv[]) 
{ 
    NSUserNotification *userNotification = [[NSUserNotification alloc] init]; 
    userNotification.title = @"Some title"; 
    userNotification.informativeText = @"Some text"; 

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification]; 

    return 0; 
} 

я скомпилировать его с:

cc -framework Foundation -o app main.m 

Он компилирует и я могу выполнить его, но он ничего не покажет. По некоторым причинам ничего не представлено. Я читал, что уведомления могут не отображаться, если приложение является основным действующим лицом. Как я могу показать уведомление?

ответ

4

установить его в качестве делегата и перезаписать

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center 
           shouldPresentNotification:(NSUserNotification *)notification { 
    return YES; 
} 
+0

могли бы вы добавить полный образец, я не уверен в понять, где поставить эту линию. –

+0

Огромное спасибо за это. Интересно, что если вы не установите делегата и не реализуете этот метод, уведомление отображается в Notification Center, но не отображается. – Ants

+0

@ Указывает, как установить делегат в python – imp

1

Я знаю, что это старый вопрос - а как там могут быть люди, которые ищут ответ, как сделать это в Python & PyObjC Я вывешу правильный синтаксис здесь (так как это один из лучших результатов Google). Поскольку я не могу комментировать комментарий imp, я отправлю это как еще один ответ.

Это можно сделать то же самое в Python с PyObjC так:

def userNotificationCenter_shouldPresentNotification_(self, center, notification): 
    return True 

Полный класс будет выглядеть следующим образом:

from Cocoa import NSObject 
import objc 

class MountainLionNotification(NSObject): 
    """ MacOS Notifications """ 
    # Based on http://stackoverflow.com/questions/12202983/working-with-mountain-lions-notification-center-using-pyobjc 

    def userNotificationCenter_shouldPresentNotification_(self, center, notification): 
     return True 

    def init(self): 

     self = super(MountainLionNotification, self).init() 
     if self is None: return None 

     # Get objc references to the classes we need. 
     self.NSUserNotification = objc.lookUpClass('NSUserNotification') 
     self.NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') 

     return self 

    def clearNotifications(self): 
     """Clear any displayed alerts we have posted. Requires Mavericks.""" 

     NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') 
     NSUserNotificationCenter.defaultUserNotificationCenter().removeAllDeliveredNotifications() 

    def notify(self, title="", subtitle="", text="", url=""): 
     """Create a user notification and display it.""" 

     notification = self.NSUserNotification.alloc().init() 
     notification.setTitle_(str(title)) 
     notification.setSubtitle_(str(subtitle)) 
     notification.setInformativeText_(str(text)) 
     # notification.setSoundName_("NSUserNotificationDefaultSoundName") 
     notification.setHasActionButton_(False) 
     notification.setActionButtonTitle_("View") 
     # notification.setUserInfo_({"action":"open_url", "value": url}) 

     self.NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self) 
     self.NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification) 

     # Note that the notification center saves a *copy* of our object. 
     return notification