I’m studying some code that Apple provided at the following link: Destination Video.
I copied the code for the PlayerController and integrated it into my app. Everything works fine, but I’m encountering the following error:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
It seems that this error occurs not only in my implementation but also in Apple’s original code. The issue appears to be related to the following class:
import SwiftUI
import AVKit
enum Presentation {
/// Presents the player as a child of a parent user interface.
case inline
/// Presents the player in full-window exclusive mode.
case fullWindow
}
/// A model object that manages the playback of video.
@MainActor @Observable class PlayerController {
/// A Boolean value that indicates whether playback is currently active.
private(set) var isPlaying = false
/// The presentation in which to display the current media.
private(set) var presentation: Presentation = .inline
/// An object that manages the playback of a video's media.
private var player: AVPlayer
/// Call the `makePlayerUI()` method to set this value.
private var playerUI: AnyObject? = nil
private var playerUIDelegate: AnyObject? = nil
/// The currently loaded video.
private(set) var currentItem: PlaylistItem? = nil
private(set) var shouldAutoPlay = true
init() {
let player = AVPlayer()
self.player = player
}
func makePlayerUI() -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.player = player
playerUI = controller
#if os(visionOS)
@MainActor
class PlayerViewObserver: NSObject, AVPlayerViewControllerDelegate {
private var continuation: CheckedContinuation<Void, Never>?
func willEndFullScreenPresentation() async {
await withCheckedContinuation {
continuation = $0
}
}
nonisolated func playerViewController(
_ playerViewController: AVPlayerViewController,
willEndFullScreenPresentationWithAnimationCoordinator coordinator: any UIViewControllerTransitionCoordinator
) {
Task { @MainActor in
await MainActor.run {
self.continuation?.resume()
}
}
}
}
let observer = PlayerViewObserver()
controller.delegate = observer
playerUIDelegate = observer
Task {
await observer.willEndFullScreenPresentation()
reset()
}
#endif
return controller
}
func loadVideo(_ channel: PlaylistItem, presentation: Presentation = .inline, autoplay: Bool = true) {
// Update the model state for the request.
currentItem = channel
shouldAutoPlay = autoplay
switch presentation {
case .fullWindow:
Task {
// After preparing for coordination, load the video into the player and present it.
replaceCurrentItem(with: channel)
}
case .inline:
// Don't SharePlay the video when playing it from the inline player,
// load the video into the player and present it.
replaceCurrentItem(with: channel)
}
// In visionOS, configure the spatial experience for either .inline or .fullWindow playback.
configureAudioExperience(for: presentation)
// Set the presentation, which typically presents the player full window.
self.presentation = presentation
}
private func replaceCurrentItem(with channel: PlaylistItem) {
// Create a new player item and set it as the player's current item.
guard let url = channel.url else {
print("unable load url")
return
}
let playerItem = AVPlayerItem(url: url)
// Set the new player item as current, and begin loading its data.
player.replaceCurrentItem(with: playerItem)
logger.debug("🍿 enqueued for playback.")
}
/// Clears any loaded media and resets the player model to its default state.
func reset() {
currentItem = nil
player.replaceCurrentItem(with: nil)
playerUI = nil
playerUIDelegate = nil
// Reset the presentation state on the next cycle of the run loop.
Task {
presentation = .inline
}
}
// MARK: - Transport Control
func play() {
player.play()
}
func seek() {
player.play()
}
func pause() {
player.pause()
}
func togglePlayback() {
player.timeControlStatus == .paused ? play() : pause()
}
/// Configures the spatial audio experience to best fit the presentation.
/// - Parameter presentation: the requested player presentation.
private func configureAudioExperience(for presentation: Presentation) {
#if os(visionOS)
do {
let experience: AVAudioSessionSpatialExperience
switch presentation {
case .inline:
// Set a small, focused sound stage when watching trailers.
experience = .headTracked(soundStageSize: .small, anchoringStrategy: .automatic)
case .fullWindow:
// Set a large sound stage size when viewing full window.
experience = .headTracked(soundStageSize: .large, anchoringStrategy: .automatic)
}
try AVAudioSession.sharedInstance().setIntendedSpatialExperience(experience)
} catch {
logger.error("Unable to set the intended spatial experience. (error.localizedDescription)")
}
#endif
}
}
in particular here:
nonisolated func playerViewController(
_ playerViewController: AVPlayerViewController,
willEndFullScreenPresentationWithAnimationCoordinator coordinator: any UIViewControllerTransitionCoordinator
) {
Task { @MainActor in // this code ---------------------
await MainActor.run {
self.continuation?.resume()
}
}
}
If you download and run the Apple code, you’ll encounter the same issue. Does anyone have any solutions or workarounds for this problem?
Thanks in advance!