Xcode Swift:当用户在后台收到本地通知时如何播放音频

问题描述

您好,我正在制作一个闹钟应用程序,当用户收到本地通知时,我正在尝试播放音频。我将所有本地通知功能和管理保存在一个名为 NotificationPublisher 的 swift 文件中。当用户前台使用应用程序时它会起作用,因为 willPresent() 函数调用,但是我试图让它在后台运行/手机关闭

当本地通知显示后台而不只是前台时,是否有一个函数会被调用

如果不是我处理这个功能错误的。

这是我的 sendNotification 函数,我可以在其中接收警报并安排本地通知。 (在我的 NotificationPublisher.swift 中)

func sendNotification(alarm : Alarm,badge: Int?) {

    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = alarm.alarmName
    notificationContent.subtitle = alarm.alarmTime + " " + alarm.alarmPeriod
    notificationContent.body = "Click here to open the app and click the solve button!"

    if let badge = badge {
        var currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber
        currentBadgeCount += badge
        notificationContent.badge = NSNumber(integerLiteral: currentBadgeCount)
    }

    notificationContent.sound = UNNotificationSound.default

    UNUserNotificationCenter.current().delegate = self

    var hour = ""
    if(alarm.alarmTime.count == 4){
        hour = String(alarm.alarmTime.prefix(1))
    } else {
        hour = String(alarm.alarmTime.prefix(2))
    }

    let minute = String(alarm.alarmTime.suffix(2))

    var intHour = Int(hour)!

    if(alarm.alarmPeriod == "PM" && intHour != 12){
        intHour += 12
    } else if(alarm.alarmPeriod  == "AM" && intHour == 12) {
        intHour = 0
    }

    var dateComponents = DateComponents()
    if(alarm.alarmDays.filter{$0}.count == 0) {
        dateComponents.hour = intHour
        dateComponents.minute = Int(minute)!
        dateComponents.timeZone = .current

        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,repeats: true) // Repeating Alarm
        let request = UNNotificationRequest(identifier: alarm.alarmKey,content: notificationContent,trigger: trigger) // replace trigger with delaytimetrigger and vice versa for exact time

        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print(error.localizedDescription)
            }
        }
    } else {
        dateComponents.hour = intHour
        dateComponents.minute = Int(minute)!
        dateComponents.timeZone = .current

        let days = ["sun","mon","tue","wed","thu","fri","sat"]
        for i in alarm.alarmDays.enumerated() {
            if(i.element){
                dateComponents.weekday = i.offset + 1

                let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,repeats: true)
                let request = UNNotificationRequest(identifier: alarm.alarmKey + days[i.offset],trigger: trigger)

                UNUserNotificationCenter.current().add(request) { error in
                    if let error = error {
                        print(error.localizedDescription)
                    }
                }
            }
        }
    }
}

这是我从 willPresent() 函数调用的 ViewController.swift 中的音频函数

func alarmSound() {
    print("alarm sound was called")

    if let player = player,player.isPlaying {
        player.stop()
    } else {
        let urlString = Bundle.main.path(forResource: "buzzer",ofType: "mp3")
        do {
            try AVAudioSession.sharedInstance().setMode(.default)
            try AVAudioSession.sharedInstance().setActive(true,options: .notifyOthersOnDeactivation)

            guard let urlString = urlString else { return }

            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlString))

            guard let player = player else { return }
            player.numberOfLoops = -1
            player.play()
        } catch {
            print(error)
        }
    }
}

解决方法

我不确定这是否可行,但我知道设置 sound 属性会更改通知的声音。请查看以下链接并分享您的反馈。

https://smashswift.com/create-custom-notification-sound/#:~:text=Scheduling%20local%20notification%20you%20need,the%20same%20with%20Push%20Notification