Digitech
Digitech

Reputation: 292

How to keep receiving the data when app is sent to background mode?

In iOS12 apple started canceling network requests if they are not URLSessionDownloadTask and setup with background session.

But according to the apple website:

You don’t have to do all background network activity with background sessions... Apps that declare appropriate background modes can use default URL sessions and data tasks, just as if they were in the foreground

I'm streaming media file with a custom player, application has Audio and Background Fetch modes enabled. URLSessionDataTask is initialized in foreground as soon as app enters background state task is canceled.

I'm aware that AVPlayer can stream in the background but using AVPlayer is not an option.

I'm aware that I can setup session with URLSessionDownloadTask which will download data in separate process and return path to file, which is not an option due the the streaming requirement.

I'm aware that I can request additional background execution time with UIApplication.shared.beginBackgroundTask but it's not acceptable solution because if backgroundTimeRemaining expires before stream finished app will be killed.

Is there any way to keep receiving data when app is in the background mode?

Upvotes: 2

Views: 1365

Answers (1)

Rob
Rob

Reputation: 437392

Make sure your background session has shouldUseExtendedBackgroundIdleMode enabled. If you don’t, the session will stop data tasks when the app transitions from foreground execution to background execution. Or, as that Downloading Files in the Background document says, you can use default session configurations, too, which don’t exhibit this behavior.


FWIW, when using AVPlayer, in addition to enabling background audio capability ...

enter image description here

... you may also have to tell the shared audio session instance that it’s active:

try AVAudioSession.sharedInstance().setCategory(.playback)
try AVAudioSession.sharedInstance().setActive(true)

I can’t say what your “custom player” requires, but for me I had to do both of these to keep the app running in the background, playing audio, with AVPlayer.

Upvotes: 0

Related Questions