Mac Mountain Lion从CLI应用程序发送通知

wma*_*but 13 cocoa objective-c nsnotificationcenter osx-mountain-lion nsusernotification

如何从命令行应用程序向通知中心发送通知?到目前为止我的尝试编译和运行,但没有成功通知我.

#import <Cocoa/Cocoa.h>

int main(int argc, const char * argv[]) {
    NSLog(@"Running notifications");

    NSUserNotification *note = [[NSUserNotification alloc] init];
    [note setTitle:@"Test"];
    [note setInformativeText:@"Woot"];

    NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
    [center scheduleNotification: note];

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我然后编译如下:

clang -framework cocoa /tmp/Notes.m
Run Code Online (Sandbox Code Playgroud)

我明白了

 2012-07-29 16:08:35.642 a.out[2430:707] Running notifications
Run Code Online (Sandbox Code Playgroud)

作为输出,但没有通知:(

这是一个因素吗?

小智 18

我发现,NSUserNotificationCenter工作时[[NSBundle mainBundle] bundleIdentifier]返回正确的标识符.所以,我写了一些你可以在https://github.com/norio-nomura/usernotification找到的混合代码

它可以在NSUserNotification没有应用程序包的情况下发送.

  • 你不必再进行混乱的方法(不再?).只需为命令行应用程序创建一个`Info.plist`文件,在构建设置中链接它并设置一些包标识符.然后设置`CREATE_INFOPLIST_SECTION_IN_BINARY`构建选项(您需要此选项,因为命令行应用程序不是包,因此不能将Info.plist包含为文件).现在`mainBundle`应该返回正确的包标识符,并且应该显示通知. (5认同)
  • 这是一个非常棒的黑客!用另一个方法替换一个方法,并欺骗运行时调用自己定义的方法.干得好先生! (2认同)