更改 Swift 中的通知声音
Changing Notification sound in Swift
我想知道是否可以更改本地通知声音。我有一个名为 notifysound.mp3 的 mp3 文件,我将它添加到我的资产文件中,但是它不起作用并且触发了默认声音。
import SwiftUI
import UserNotifications
struct Alert: View {
@State var noon = false
func noonNotify() {
let content = UNMutableNotificationContent()
content.title = "Meds"
content.subtitle = "Take your meds"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.mp3"))
var dateComponents = DateComponents()
dateComponents.hour = 12
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
}
var body: some View {
VStack {
Toggle(isOn: $noon) {
Text("Noon")
}
.onChange(of: Prime) { newValue in
if newValue {
noonNotify()
}
}
Button("Request Permission") {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
}
}
}
我尝试重命名文件并添加扩展名,但没有任何效果。有人知道为什么它不起作用吗?
不支持 MP3 文件。您需要少于 30 秒的 wav、caf 或 aiff。文档中的更多详细信息:https://developer.apple.com/documentation/usernotifications/unnotificationsound
我想知道是否可以更改本地通知声音。我有一个名为 notifysound.mp3 的 mp3 文件,我将它添加到我的资产文件中,但是它不起作用并且触发了默认声音。
import SwiftUI
import UserNotifications
struct Alert: View {
@State var noon = false
func noonNotify() {
let content = UNMutableNotificationContent()
content.title = "Meds"
content.subtitle = "Take your meds"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.mp3"))
var dateComponents = DateComponents()
dateComponents.hour = 12
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
}
var body: some View {
VStack {
Toggle(isOn: $noon) {
Text("Noon")
}
.onChange(of: Prime) { newValue in
if newValue {
noonNotify()
}
}
Button("Request Permission") {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
}
}
}
我尝试重命名文件并添加扩展名,但没有任何效果。有人知道为什么它不起作用吗?
不支持 MP3 文件。您需要少于 30 秒的 wav、caf 或 aiff。文档中的更多详细信息:https://developer.apple.com/documentation/usernotifications/unnotificationsound