CodexBloom - Programming Q&A Platform

Unexpected App Crashes with AVPlayer in Background Mode on iOS 17

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
ios avplayer background-audio swift

I've been struggling with this for a few days now and could really use some help. I'm experiencing frequent crashes in my iOS app when using `AVPlayer` to stream audio while the app is in the background. This seems to happen only on iOS 17 devices. The crash log shows: `EXC_BAD_ACCESS (code=1, address=0x0)`, which makes it difficult to pinpoint the exact cause. I've set up the `AVPlayer` as follows: ```swift import AVFoundation class AudioPlayer { var player: AVPlayer? func setupPlayer(with url: URL) { player = AVPlayer(url: url) } func play() { player?.play() } func pause() { player?.pause() } } ``` I ensure that the player is properly initialized before calling `play()`. I've also added the required background modes in my app's Info.plist: ```xml <key>UIBackgroundModes</key> <array> <string>audio</string> </array> ``` However, the crashes typically happen after the app has been in the background for a few minutes, and I need to replicate the scenario consistently in the debugger. I've tried wrapping my `play()` and `pause()` calls in `DispatchQueue.main.async` since I read that UI-related tasks should be done on the main thread, but that hasn't resolved the scenario. Additionally, I've been monitoring the system notifications for interruptions and buffering. Here's what I have for observing notifications: ```swift NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil) ``` Despite this, the crashes continue, seemingly unrelated to any interruptions. Is there a known scenario with `AVPlayer` in the background on iOS 17, or any best practices I might be missing? Any pointers on debugging memory management issues with `AVPlayer` would also be greatly appreciated. I'm working on a CLI tool that needs to handle this. What's the best practice here? I'm working on a web app that needs to handle this. What's the best practice here?