我正在制作一个音乐流闹钟。音乐在用户选择的持续时间内流动,包括在后台,并且在持续时间结束时,除了本地通知之外,还会播放自定义警报声音。
简而言之 (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")
}
Edit 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
})
}