有几篇文章解决了同样的问题,但是(据我所见)它们都是 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)
}
}
}