Programmatically check state of do not disturb on OS X

前端 未结 4 1115
悲&欢浪女
悲&欢浪女 2021-02-04 11:35

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

相关标签:
4条回答
  • 2021-02-04 11:44

    In Objective-C, you can access the value like this:

    NSUserDefaults* defaults = [[NSUserDefaults alloc]initWithSuiteName:@"com.apple.notificationcenterui"];
    BOOL dnd = [defaults boolForKey:@"doNotDisturb"];
    
    0 讨论(0)
  • 2021-02-04 11:45

    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.

    0 讨论(0)
  • 2021-02-04 11:53

    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") {
        // ...
    }
    
    0 讨论(0)
  • 2021-02-04 12:05

    Swift 4

    UserDefaults(suiteName: "com.apple.notificationcenterui")?.bool(forKey: "doNotDisturb")
    
    0 讨论(0)
提交回复
热议问题