【问题标题】:How to keep UNUserNotificationCenter sound playing until user stops it如何保持 UNUserNotificationCenter 声音播放直到用户停止它
【发布时间】:2018-09-22 17:59:59
【问题描述】:

有几篇文章解决了同样的问题,但是(据我所见)它们都来自 4 年前的 Objective-C。我正在使用 Swift 4.2。

我正在制作一个倒数计时器应用程序。当应用程序在后台并且计时器到期时,我希望通知声音继续播放,直到用户通过点击通知停止它。

到目前为止,我只从背景/锁屏播放一次警报声。

这是我正在使用的方法。

func notifications(title: String, message: String){

    center.delegate = self

    let restartAction = UNNotificationAction(identifier: "RESTART_ACTION", title: "Restart timer", options: UNNotificationActionOptions(rawValue: 0))

    let stopAction = UNNotificationAction(identifier: "STOP_ACTION", title: "Stop", options: UNNotificationActionOptions(rawValue: 0))

    let expiredCategory = UNNotificationCategory(identifier: "TIMER_EXPIRED", actions: [restartAction, stopAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))

    // Register the notification categories.
    center.setNotificationCategories([expiredCategory])

    let content = UNMutableNotificationContent()
    content.title = title
    content.body = message
    content.categoryIdentifier = "TIMER_EXPIRED"
    content.sound = UNNotificationSound(named:UNNotificationSoundName(rawValue: _currentTimer.getSoundEffect+".mp3"))

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(_currentTimer.endTime), repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    center.add(request) { (error : Error?) in
        if let theError = error {
            print(theError.localizedDescription)
        }
    }
}

【问题讨论】:

  • 如果你的时间间隔小于 60 秒,它会崩溃。这是设计使然。您使用的时间间隔是多少?
  • 它是可变的。时间间隔由用户输入并存储在 _currentTimer.endTime 中。这是计时器将用完的时间(以秒为单位)。
  • 不过,我不想让 20 分钟的计时器重新启动。不是这样的。我想要一个 20 分钟的计时器,并一直持续到用户将其静音。
  • 我的意思是,如果它因为您将repeat 设置为true 而崩溃,那么很可能是因为 timeInterval 小于 60 秒。您仍然没有回答您的timerInterval 崩溃时的用途。你能回答吗?
  • 当然。在这种情况下,它不到 60 秒。大概是5秒。用户可以在他/她想要的任何时间设置一个计时器。

标签: ios unusernotificationcenter swift4.2


【解决方案1】:

所以,我要解决这个问题的答案是没有答案。 Apple 不希望第三方开发者在任何情况下播放通知声音超过 30 秒,即使是要构建一个计时器应用程序。他们在时钟应用程序中的计时器将一直关闭,直到您将其静音,但第三方开发人员不得这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多