How to call a function when the app is inactive (e

2020-05-01 08:54发布

问题:

I am making a music-streaming alarm clock. Music streams for the duration selected by the user, including in the background, and at the end of the duration a custom alarm sound is played in addition to a local notification.

In short (1) set timer (2) local notification fires off (3) streamed music stops (4) alarm plays

I am able to do (1) and (2) ok, but am unable to figure out how to trigger (3) or (4) when the app is in the background.

Here is the code for (1) and (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)

Your help much appreciated.

Edit 1: Timer trial. Only was able to get it to work when app is in foreground.

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!