【发布时间】: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