从OS X通知中心获取通知列表

4

需要澄清的是,读取自己拥有/预定的用户通知非常简单。但是其他通知则会成为问题。 - Vervious
你说得对,我没有提到我需要收到“任何”通知。 - Stéphane Bruckert
2个回答

6

目前没有公开的API。因此,无法符合App Store的要求。

但是

作为我小型技术演示应用程序DiscoNotifier(我以对通知进行键盘LED闪烁响应)的一部分,我编写了一个DDUserNotificationCenterMonitor类

参见:https://github.com/Daij-Djan/DiscoNotifier/tree/master/DiscoNotifier

它使用FileSystemEvents和SQLite工作,并检查通知中心的数据库

它可以工作,并且数据库具有所有信息(表:presented_notifications),但是这很脆弱且私有


3
感谢Daij-Djan的回答,我找到了通知中心的偏好设置在SQLite数据库中~/Library/Application Support/NotificationCenter/
为了读取这个数据库,我们可以使用FMDB,你可以在pod中找到它。
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"

获取数据库文件并打开。
NSString *pathToNCSupport = [@"~/Library/Application Support/NotificationCenter/" stringByExpandingTildeInPath];
NSError *error = nil;
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToNCSupport error:&error];    //find the db

FMDatabase *database = nil;
for (NSString *child in contents) {
    if([child.pathExtension isEqualToString:@"db"]) {
        database = [FMDatabase databaseWithPath:[pathToNCSupport stringByAppendingPathComponent:child]];
        if([database open]) {
            printf("Opening Notification Center");
            [database close];
            break;
        }
    }
}

执行任何SQL查询:

if([database open]) {
    FMResultSet *rs = [database executeQuery:@"select count(*) as cnt from presented_notifications"];
    while ([rs next]) {
        int cnt = [rs intForColumn:@"cnt"];
        NSLog(@"Total Records :%d", cnt);
    }

    [database close];
}

Github 上完成项目。


这种方法在2020年还有效吗?如果不行,现在有没有其他方法可以做到呢? - Vijay Raghavan
这个文件夹在文图拉中不存在。我猜它已经不再有效了。 - siniradam
我明白了:https://dev59.com/koTca4cB1Zd3GeqPAuZU - siniradam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接