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