Mac Swift video player run time error

Hello this code is working on Xcode but when it crashing on run time, what is the problem

import SwiftUI
import AVKit

struct ContentView: View {
var body: some View {
let player = AVPlayer()

    VideoPlayer(player: player)
        .onAppear{
          if player.currentItem == nil {
                let item = AVPlayerItem(url: URL(string: "url")!)
                player.replaceCurrentItem(with: item)
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                player.play()
            })
        }
    LandmarkList()
        .frame(minWidth: 700, minHeight: 300)
}

}

#Preview {
ContentView()
.environment(ModelData())
}

Have you tried using a different video?

What codec/format does the video use?

To @idrises ,

The issue in your code seems to be with how the AVPlayerItem is being created and used, as well as potential issues with the URL string and timing. Here are some steps to diagnose and fix the issue.
Ensure that the URL string you are using is valid. If it’s not, it will cause the app to crash at runtime. It’s better to initialize and configure the AVPlayer and AVPlayerItem outside of the body to avoid recreating them every time the view updates. Make sure to safely unwrap the URL to avoid force unwrapping which can cause crashes if the URL is invalid.

Additional Considerations Make sure the URL points to a valid video resource. Add print statements or breakpoints to help identify the exact cause of the runtime error. Ensure asynchronous code (like DispatchQueue.main.asyncAfter) is used appropriately to avoid timing issues.

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.