微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Swift 中更改通知声音

如何解决在 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。