UNMutableNotificationContent with custom sound

Viewed 2205

I'm trying to create a simple demo where I click a button, and a custom notification appears, accompanied with a custom sound.

The behaviour that happens:

  • The notification appears properly on both emulator and connected device (iPhone SE)
  • The standard sound plays on emulator, but not on the device.
  • The custom sound does not play at all. On the emulator I get the default notification sound, while on the device I don't get any sound at all.

The sound file 'alert.caf' was added to the Assets.xcassets.

This is my class (access rights have been handled in the app launch callback):

import UIKit
import UserNotifications

class HomeViewController: UIViewController, UNUserNotificationCenterDelegate {

    @IBOutlet weak var btnNotification: UIButton!

    @IBAction func triggerNotification(_ sender: Any) {
        /* let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil) */
        execNotification()

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UNUserNotificationCenter.current().delegate = self

    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler:
        @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert,.sound])
    }

    private func execNotification() {
        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = "UNUserNotification Sample"
        notificationContent.body = "Sample test msg"
        notificationContent.badge = 0
        notificationContent.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "alert.caf"))
        notificationContent.categoryIdentifier = "GENERAL"

        let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)
        let notificationRequest = UNNotificationRequest(identifier: "general", content: notificationContent, trigger: notificationTrigger)

        // Add Request to User Notification Center
        UNUserNotificationCenter.current().add(notificationRequest) { (error) in
            if let error = error {
                print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
            }
        }

    }

}

Note: I checked all settings that may have cause the alert not to be played, but there really is no reason. The app settings are correct, there is no "Do not disturb" mode on.

I use Xcode 10.1

2 Answers

I also could not setup custom sound with only difference that i was developing app for macOS.

My setup: macOS Big Sur 11.4 Xcode 12.5

Solution: Custom sound was played only by adding 'wav' file to project ('caf' did not work) and then restarting mac.

Considering similarities between iOS and mac platforms i would suggest to add 'wav' file to the project + restart iPhone.

A few tips to note:

  • Make sure the sound file is located in the current executable’s main bundle or in the Library/Sounds directory of the current app container directory (source).

  • Make sure the sound file is less than 30 seconds. If the sound file is longer than 30 seconds, the system plays the default sound instead (source).

  • Make sure the sound file is added in your target's "Copy Bundle Resources" in Build Phases.

  • Select the sound file and make sure in its "Target Membership" your app's target is properly selected.

Related