我正在制作音乐流式闹钟。在用户选择的持续时间内的音乐流,包括在后台,并且在持续时间结束时,除本地通知外,还会播放自定义警报声音。
简而言之(1)设置计时器(2)触发本地通知(3)流音乐停止(4)警报播放
我可以执行(1)和(2),但无法弄清楚当应用程序在后台时如何触发(3)或(4)。
这是(1)和(2)的代码
let center = UNUserNotificationCenter.current()
var trigger : UNNotificationTrigger!
//...
trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.hour, .minute], from: date), repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
非常感谢您的帮助。
编辑1:计时器试用。仅当应用程序处于前台时才能够使它工作。
if let interval = AppDataManager.shared.wakeupDate?.timeIntervalSince(Date.init()) {
print("interval ", interval)
self.wakeUpTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { (timer) in
print("Timer Invoked")
self.stopPlay()
}
} else {
print("interval NOT AVAILABLE")
}
编辑2:
print ("Wakeup date set is \(AppDataManager.shared.wakeupDate)")
print ("Date now is \(Date())")
let calendar = Calendar.current
let unitFlags = Set<Calendar.Component>([ .second])
let datecomponents = calendar.dateComponents(unitFlags, from: Date(), to: AppDataManager.shared.wakeupDate!)
let seconds = datecomponents.second
print(String(describing: seconds))
let secondsInDouble: Double = Double(seconds!)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if appDelegate.globalTimer == nil {
print ("Timer started")
appDelegate.globalTimer = Timer.scheduledTimer(withTimeInterval: secondsInDouble, repeats: false, block: {_ in
NSLog("Right now the music should stop! ????")
//Function for music stop. This only works in Simulator, or when the app is active in the device
})
}