0

An AVAudioPlayer is stopped in a background tasks when the app transitions to background:

func stop() {

    var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
    backgroundTask = UIApplication.shared.beginBackgroundTask() {

        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid
    }

    DispatchQueue.global(qos: .default).async {

        self.audioPlayer?.pause()

        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskInvalid // Symbolic breakpoint stops here
    }
}

The function above gets called by the view controller that contains the AVAudioPlayer when a UIApplicationDidEnterBackground notification is posted.

Still I get an error at line backgroundTask = UIBackgroundTaskInvalid:

// Can't endBackgroundTask: no background task exists with identifier 1f, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.`

When I remove the line I get no errors. I looked through similar questions on SO but they did not help.

What is causing this error?

Manuel
  • 14,274
  • 6
  • 57
  • 130
  • your background task is already ended in your first block of code then you are ending it again may be this is the cause for the error. – Sunil M. Sep 11 '17 at 05:47
  • @iOSDev I put a breakpoint on the code inside the termination handler, from that I can tell that it doesn't seem to be executed. – Manuel Sep 11 '17 at 16:51
  • I found a solution. I hope it helps. https://stackoverflow.com/a/58763049/1890317 – uplearned.com Nov 08 '19 at 08:46

0 Answers0