I am working on an iOS app (an alarm clock), where I need to play a custom notification sound that is downloaded by the app after it has been installed. Here’s the relevant part of the code:
let notificationContent = UNMutableNotificationContent()
...
notificationContent.sound = UNNotificationSound(named: myLocalFile)
This works fine when myLocalFile
is part of the app bundle, but I need to play sounds that are downloaded by the app. Here’s some additional context:
- The app generates custom AI sounds for alarms that are specific to the user.
- The app downloads these sounds and needs to play them when the alarm triggers.
- The alarm must play in all scenarios where the phone is on, including:
- Foreground and background
- Screen lock
- After reboot
- Ideally, I’d like to display a full-screen alarm UI (but haven’t been able to figure out how to do this). Any guidance on that would be appreciated as well.
- For now, I am simulating the alarm using a notification, but I am limited to playing sounds from the app bundle.
How can I play these downloaded custom sounds in the notification, and is there a way to achieve a full-screen alarm UI?
0
Since notifications can’t use downloaded sounds, one option is to manually play the downloaded sound when the notification is triggered.
I observe the notification using UNUserNotificationCenterDelegate and play the sound manually using AVAudioPlayer. Example:
// Observe when the notification is received
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play the downloaded sound manually
playDownloadedSound()
// Complete with notification options (vibration, badge, etc.)
completionHandler([.badge, .banner, .list])
}
func playDownloadedSound() {
guard let soundURL = // URL to your downloaded sound
else { return }
do {
let player = try AVAudioPlayer(contentsOf: soundURL)
player.play()
} catch {
print("Error playing sound: (error)")
}
}