在本地通知上发送带有自定义声音的触觉
Posted
技术标签:
【中文标题】在本地通知上发送带有自定义声音的触觉【英文标题】:Send Haptics with Custom Sound on Local Notification 【发布时间】:2019-11-29 16:19:08 【问题描述】:我有一个应用程序,我会在指定时间发送通知以帮助用户记住事情。在通知中实现自定义声音时遇到问题。当手机的铃声打开时,我会播放声音,但是我想让它在发送时播放触觉反馈。无论铃声是否打开,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】:实现UNUserNotificationCenterDelegate
的userNotificationCenter(_center:willPresent:withCompletionHandler)
您可以通过两种方式为通知传递没有声音效果并播放自己的声音。
忽略设备中的静音模式
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
但它仅在应用程序处于前台时才有效。我认为您无法为警报发送触觉和振动效果。
【讨论】:
以上是关于在本地通知上发送带有自定义声音的触觉的主要内容,如果未能解决你的问题,请参考以下文章