How to call a function when the app is inactive (e.g. playing music in background)?

时光毁灭记忆、已成空白 提交于 2020-04-07 08:25:29

问题


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! 🚨🚨🚨🚨")
                //Function for music stop. This only works in Simulator, or when the app is active in the device
            })
        }

来源:https://stackoverflow.com/questions/60779133/how-to-call-a-function-when-the-app-is-inactive-e-g-playing-music-in-backgroun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!