Programmatically check state of do not disturb on OS X

前端 未结 4 1129
悲&欢浪女
悲&欢浪女 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: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.

提交回复
热议问题