CodexBloom - Programming Q&A Platform

AVPlayer not properly resuming playback after background mode on iOS 17

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
ios avplayer audio-session avfoundation swift

I'm wondering if anyone has experience with I'm working on a personal project and I tried several approaches but none seem to work..... I'm encountering an issue where my `AVPlayer` instance does not resume playback correctly after the app returns from the background on iOS 17. I have implemented the `AVAudioSession` correctly and set the category to `playback`, but when I return to the app after a short time, the player doesn't start where it left off. Instead, it keeps displaying the last position before going to the background. Here’s a snippet of my setup: ```swift import AVFoundation class VideoPlayerViewController: UIViewController { var player: AVPlayer! var playerItem: AVPlayerItem! override func viewDidLoad() { super.viewDidLoad() setupAudioSession() configurePlayer() } func setupAudioSession() { do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) try AVAudioSession.sharedInstance().setActive(true) } catch { print("Error setting up audio session: \(error)") } } func configurePlayer() { guard let url = URL(string: "https://example.com/video.mp4") else { return } playerItem = AVPlayerItem(url: url) player = AVPlayer(playerItem: playerItem) player.play() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) player.pause() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) player.seek(to: playerItem.currentTime()) player.play() } } ``` I've also tried implementing the `UIApplicationDidBecomeActiveNotification` to handle resuming playback, but it seems to trigger too late or not at all. Here is how I'm observing the notification: ```swift NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) @objc func appDidBecomeActive() { player.seek(to: playerItem.currentTime()) if player.timeControlStatus != .playing { player.play() } } ``` When testing, I noticed that sometimes the player will not resume, and I see a "Player has no current item" error in the console. I don't have any strong references to the player item after going to the background. What am I missing? Is there a specific setting or method I should be using to ensure proper playback resumption on iOS 17? Any insights would be greatly appreciated. I'm working on a web app that needs to handle this. Any help would be greatly appreciated! Any ideas what could be causing this? Any ideas what could be causing this?