Reputation: 1010
I have an app where I send notifications at specified times to help users remember things. I'm running into a problem when implementing custom sounds in my notifications. I have the sound playing when the phone's ringer is on, however I want to have it play a haptic feedback when it delivers. The iOS default sound plays a haptic when it delivers whether or not the ringer is on or not.
My code looks like this:
var sounds = ["default", "definite", "quite-impressed", "rush", "serious-strike", "what-friends-are-for"]
var sound = 0
let soundNumber = defaults.integer(forKey: "alarmSound")
let notificationContent = UNMutableNotificationContent()
notificationContent.title = defaults.string(forKey: "notificationBody") ?? "Time to eat!"
notificationContent.body = defaults.string(forKey: "notificationText") ?? "Your timers have gone off!"
if sound == 0 {
notificationContent.sound = UNNotificationSound.default
} else {
notificationContent.sound = UNNotificationSound.init(named: UNNotificationSoundName(rawValue: "\(sounds[sound]).m4a"))
}
notificationContent.categoryIdentifier = NotificationActions.Category.snooze
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: differenceInDates, repeats: false)
let request = UNNotificationRequest(identifier: "\(i)", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
The sounds array is an array of the sound file names, it gets the index of the sound from UserDefaults and sets the notification sound with that file.
Appreciate any help!
Upvotes: 0
Views: 734
Reputation: 2409
Implementing userNotificationCenter(_center:willPresent:withCompletionHandler)
of UNUserNotificationCenterDelegate
you could pass no sound effect for notification and play your own instead in two ways.
Ignoring silent mode in you device
var sound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL, &sound)
AudioServicesPlaySystemSound(sound)
Or only when silent mode off
let audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.volume = 1.0
audioPlayer?.play()
Setup in AppDelegate file
import UserNotifications
.......
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
.......
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .alert])
// play sound here
}
}
But it will work only when app is in foreground. I think you could not send haptics and vibration effects for your alerts.
Upvotes: 0