It's possible to send notifications to the Notification Center on Mac using NSUserNotification and NSUserNotificationCenter API classes.
But is there any way of reading the notifications from the Notification Center?
It's possible to send notifications to the Notification Center on Mac using NSUserNotification and NSUserNotificationCenter API classes.
But is there any way of reading the notifications from the Notification Center?
There is no public API for that. So nothing App Store conform.
BUT
As part of my little tech-demo-app DiscoNotifier (where I flash the keyboard LEDs in response to a notification) I wrote a DDUserNotificationCenterMonitor class
see: https://github.com/Daij-Djan/DiscoNotifier/tree/master/DiscoNotifier
it works using FileSystemEvents and SQLite and checks the notification center's database
It works and the database has all info (table: presented_notifications) but.. this is fragile AND private
Thanks to Daij-Djan's answer, I could figure out that the preferences for the notification center are located in a SQLite database in ~/Library/Application Support/NotificationCenter/
.
To read this database, we can use FMDB which you will find as a pod.
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
Get the DB file and open it.
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;
}
}
}
Launch any SQL query:
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];
}
Complete project on Github.