I want to play remote videos using an AVPlayer in my SwiftUI App. However, I can't fix the error:
"Main thread blocked by synchronous property query on not-yet-loaded property (PreferredTransform) for HTTP(S) asset. This could have been a problem if this asset were being read from a slow network."
My code looks like this atm:
struct CustomVideoPlayer: UIViewControllerRepresentable {
let myUrl: URL
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: Context) -> AVPlayerViewController {
let playerItem = AVPlayerItem(url: myUrl)
let player = AVQueuePlayer(playerItem: playerItem)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
context.coordinator.setPlayerLooper(player: player, templateItem: playerItem)
playerViewController.delegate = context.coordinator
playerViewController.beginAppearanceTransition(true, animated: false)
return playerViewController
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
static func dismantleUIViewController(_ uiViewController: AVPlayerViewController, coordinator: ()) {
uiViewController.beginAppearanceTransition(false, animated: false)
}
class Coordinator: NSObject, AVPlayerViewControllerDelegate {
var parent: CustomVideoPlayer
var player: AVPlayer? = nil
var playerLooper: AVPlayerLooper? = nil
init(_ parent: CustomVideoPlayer) {
self.parent = parent
super.init()
}
func setPlayerLooper(player: AVQueuePlayer, templateItem: AVPlayerItem) {
self.player = player
playerLooper = AVPlayerLooper(player: player, templateItem: templateItem)
}
}
}
I already tried creating the AVPlayerItem/AVAsset on a background thread and I also tried loading the properties asynchronously before setting the player in makeUIViewController:
let player = AVQueuePlayer(playerItem: nil)
...
Task {
let asset = AVAsset(url: myUrl)
let _ = try await asset.load(.preferredTransform)
let item = AVPlayerItem(asset: asset)
player.replaceCurrentItem(with: item)
}
Nothing seems to fix the issue (btw: the main thread is actually blocked, there is a noticable animation hitch).
Any help is much appreciated.