Using Objective-C, how can I programmatically check the state of the system \"Do Not Disturb\" setting on OS X? I\'m fine with using hacks or private APIs since I don\'t need to
In Objective-C, you can access the value like this:
NSUserDefaults* defaults = [[NSUserDefaults alloc]initWithSuiteName:@"com.apple.notificationcenterui"];
BOOL dnd = [defaults boolForKey:@"doNotDisturb"];
This answer describes how to read and write the state of Do Not Disturb using the command line.
Note that the filename contains your Mac's Hardware UUID. For simplicity, it's a constant in the code below. You can figure it out using the built-in System Information app. There are also different ways to get it programmatically, like this, which I haven’t tried yet.
Using Swift, the content of the plist file can be read as NSDictionary
as follows:
import Foundation
// Get path to file
let uuid = "00000000-0000-0000-0000-000000000000"
let filepath = "~/Library/Preferences/ByHost/com.apple.notificationcenterui.\(uuid).plist".stringByExpandingTildeInPath
// Load file as `NSDictionary`
if let dict = NSDictionary(contentsOfFile: filepath) {
// Get state of Do Not Disturb
let doNotDisturbState = dict["doNotDisturb"] as? Bool
println(doNotDisturbState)
}
When I tested it, it sometimes took several seconds for the content of the plist file to be updated, hence you won't get the new state immediately after it changed.
You can (and should) simply use UserDefaults:
let theDefaults = UserDefaults(suiteName: "com.apple.notificationcenterui")
print(theDefaults?.bool(forKey: "doNotDisturb"))
For time-controlled switching you should check if the minute of the day lies between dndStart
and dndEnd
:
let theDefaults = UserDefaults(suiteName: "com.apple.notificationcenterui")
let theDate = Date()
let theCalendar = Calendar.current
let theHour = calendar.component(.hour, from: theDate)
let theMinute = calendar.component(.minute, from: theDate)
let theMinuteOfDay = Double(theHour * 60 + theMinute)
if theMinuteOfDay >= theDefaults.double(forKey: "dndStart") &&
theMinuteOfDay <= theDefaults.double(forKey: "dndEnd") {
// ...
}
Swift 4
UserDefaults(suiteName: "com.apple.notificationcenterui")?.bool(forKey: "doNotDisturb")