在本地通知上发送带有自定义声音的触觉

时间:2019-11-29 16:19:08

标签: ios notifications uilocalnotification

我有一个应用程序,可以在指定的时间发送通知,以帮助用户记住事情。在通知中实现自定义声音时遇到问题。当手机的铃声打开时,我会播放声音,但是我想让它在播放时播放出触觉反馈。不管铃声是否开启,iOS默认声音都会播放触觉。

我的代码如下:

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)

sounds数组是声音文件名的数组,它从UserDefaults获取声音的索引,并使用该文件设置通知声音。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

实施userNotificationCenter(_center:willPresent:withCompletionHandler)中的UNUserNotificationCenterDelegate,您可能不会传递任何声音效果来进行通知,而是通过两种方式播放自己的声音。

忽略设备中的静音模式

var sound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL, &sound)
AudioServicesPlaySystemSound(sound)

或者仅当静音模式关闭时

let audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.volume = 1.0
audioPlayer?.play()

在AppDelegate文件中设置

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
    }
}

但是它仅在应用程序处于前台时才起作用。我认为您无法为警报发送触觉和振动效果。