When a user uses "Do not disturb" mode, your notifications no longer get sound and banner, unless your app can post a Critical Alert.
However, to get the entitlement of critical alert, you have to ask Apple to give your permission. Someone complains that their requests to Apple even took months without a response.
I found a new way to get the permission directly from the user, instead of Apple.
Steps
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .criticalAlert]) { granted, error in
guard error == nil else {
DispatchQueue.main.async {
NSSound.beep()
let alert = NSAlert(error: error!)
alert.runModal()
}
return
}
}
Above code will get an error as you don't have the entitlement of critical alert. But we could use code below:
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert]) { granted, error in
guard error == nil else {
DispatchQueue.main.async {
NSSound.beep()
let alert = NSAlert(error: error!)
alert.runModal()
}
return
}
if granted {
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .criticalAlert]) { granted, error in
/* You will get an error here as you don't have the critical alert entitlement.
But since you have already got the permission for normal notifications, you now get a disabled critical alert permission.
You are just one step to the critical alert. Ask your user to manually enable the permisssion.
The error should be igonred here.
*/
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.criticalAlertSetting != .enabled {
DispatchQueue.main.async {
NSSound.beep()
showCriticalAlert = true
}
}
}
}
}
}
We request the permission twice. First, we request the common notification permission. When a user allow that, we request the critical alert permission. Since we have already got the common notification permission the second permission request won't pop up. Also as we don't have critical alert entitlement from Apple, we will get an error. But the error can be ignored. Then when you open the app's notification settings, there is a critical alert permission, with disabled state. So what you only need to do is to show an alert and ask the user to enable the critical alert if the user wants to get notified in "Do not disturb" mode.
Sample App
I have already got an sample app on sale in App Store. You can try it for free.
Stand Reminder