Programmatically check state of do not disturb on OS X

前端 未结 4 1190
悲&欢浪女
悲&欢浪女 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: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") {
        // ...
    }
    

提交回复
热议问题