CodexBloom - Programming Q&A Platform

How to implement guide with avplayer not seeking correctly after backgrounding on ios 16.5

๐Ÿ‘€ Views: 82 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-24
iOS AVPlayer backgrounding Swift

I'm stuck on something that should probably be simple. I'm working with an scenario where my AVPlayer instance does not seek correctly after the app has been backgrounded and then brought back to the foreground. The player is supposed to resume playback from the last sought position, but instead, it seems to jump back to the start of the video. I have implemented the following code to handle backgrounding: ```swift func applicationDidEnterBackground(_ application: UIApplication) { if let currentItem = player.currentItem { let currentTime = player.currentTime() UserDefaults.standard.set(currentTime.seconds, forKey: "lastPlaybackTime") UserDefaults.standard.set(currentItem.asset as! AVURLAsset, forKey: "lastPlayedAsset") } } ``` And in my view controller, I attempt to seek to the saved time when the app becomes active again: ```swift func applicationDidBecomeActive(_ application: UIApplication) { if let lastPlaybackTime = UserDefaults.standard.value(forKey: "lastPlaybackTime") as? Double, let lastPlayedAsset = UserDefaults.standard.value(forKey: "lastPlayedAsset") as? AVURLAsset { player.replaceCurrentItem(with: AVPlayerItem(asset: lastPlayedAsset)) player.seek(to: CMTime(seconds: lastPlaybackTime, preferredTimescale: 1)) player.play() } } ``` Despite this, when I resume the app, the video always starts from the beginning. I checked the values stored in UserDefaults and they are correct, but the player just doesnโ€™t seek to them. Additionally, there are no behavior messages in the console. Iโ€™ve tried moving the seek logic to different lifecycle methods, but it hasnโ€™t helped. Is there a specific configuration or pattern I should be following for AVPlayer when dealing with backgrounding and resuming? Any advice would be greatly appreciated!