gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:16:48 31 4
gpt4 key购买 nike

我有一个应用程序,我可以在指定时间发送通知以帮助用户记住事情。我在通知中实现自定义声音时遇到问题。当手机铃声打开时,我会播放声音,但我想让它在通话时播放触觉反馈。无论铃声是否打开,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)

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

感谢任何帮助!

最佳答案

实现 UNUserNotificationCenterDelegateuserNotificationCenter(_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
}
}

但只有当应用程序位于前台时它才会起作用。我认为您无法发送警报的触觉和振动效果。

关于ios - 在本地通知上发送带有自定义声音的触觉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108191/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com