I'm making an alarm clock app, and I have confirmed that my alarm notifications are being triggered correctly, but the sound does not always play as I expect.
For instance, when the phone is not in silent mode, the notification plays the sound sucessfully (ok, great!). However, when the phone is in silent mode, the sound does not play, even though the app is still running in the background (not so great...).
I understand that silent mode is supposed to silence all notification sounds, BUT I've downloaded other alarm clock apps from the App Store (like Alarmy), and they are somehow able to get their notification sounds to play even if the phone is on silent mode, as long as the app is still running in the background. Only when the app is fully exited will the silent mode take effect.
Does anyone know how to achieve this result? Is there some setting or option that I need to declare either in my code or plist file? I've scoured the internet but haven't found anything for this particular issue...
My code to set the AVAudioSession category:
private func setAudioCategory() {
do {
// Enable sound (even while in silent mode) as long as app is in foreground.
try AVAudioSession.sharedInstance().setCategory(.playback)
}
catch {
print(error.localizedDescription)
}
}
My code to set a notification:
/// Sets a local user notification for the provided `Alarm` object.
static func set(_ alarm: Alarm) {
// Configure the notification's content.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: K.Keys.notificationTitle, arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: K.Keys.notificationBody, arguments: nil)
// Get sound name
let soundName: String = UserDefaultsManager.getAlarmSound().fileNameFull
// Set sound
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: soundName))
content.categoryIdentifier = "Alarm"
// Configure the time the notification should occur.
var date = DateComponents()
date.hour = alarm.hour
date.minute = alarm.minute
// Create the trigger & request
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
let request = UNNotificationRequest(identifier: alarm.notifID, content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: { error in
if error != nil {
// TODO: Show Alert for Error
return
}
})
}
.playAndRecord
and enabling Audio in the .plist file forRequired Background Modes
does not seem to work... (from "Microphone method" in linked article). – Supper