SwiftUI background mode works in simulator but not on a real device?

I'm playing an Audio in my app.

I can play the audio in the background mode in the simulator but when I test the app in a real device, the audio Stops as soon as the App goes in the background.

    1. Xcode 14
    1. iOS 16
    1. Device: iPhone 11

I have this in the background mode:

This is the code into .onAppear() view:

let path = Bundle.main.path(forResource: "timer.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
timerEffect = try AVAudioPlayer(contentsOf: url) //@State var timerEffect: AVAudioPlayer?
timerEffect?.numberOfLoops = -1
timerEffect?.play()

Anyone can help me? Thanks!

Accepted Reply

This guide works: https://betterprogramming.pub/dont-stop-the-music-in-an-ios-app-bc4780f6cf61

Replies

Same here. My app is written in Objective-C (most of it), has location updates and audio background mode. When testing in iOS 16 beta 7, I can reproduce the issue. The app plays a warning when approaching some locations while driving. In a long trip I did today while I was testing the app on the road, I could reproduce the issue all the time. Audio is working on the foreground, but as soon as I lock the device, audio does not work. I have just tested in the simulator, and in the simulator it is working fine.

Background audio has worked in my app in the last releases of iOS with no issue. It is the same code I am using with iOS 16 beta 7.

Any idea? Thank you.

Well after more testing, background audio is working for me. What seems different between iOS 15 and 16 is:

[AVAudioSession sharedInstance].currentRoute.outputs

In iOS 15, it seemed to work in the background and with not activation of the audio session, so I could check if the device was connected to CarPlay. It seems that in iOS 16 it doesn't work that way, so I have changed my code to compensate. This is what caused for me that audio did not seem to work, I was sending the audio to a route different from CarPlay, when the device was connected to CarPlay.

Regarding the original question, do you have an active Audio Session when you are in the background?

  • I never used Audio Session, I have to try!

Add a Comment

This guide works: https://betterprogramming.pub/dont-stop-the-music-in-an-ios-app-bc4780f6cf61