swift – SwiftUI VideoPlayer Not Refreshing with Up to date URL on iOS

Spread the love

I am working into a difficulty with SwiftUI’s VideoPlayer the place it doesn’t refresh when its binding URL is up to date. The video solely updates appropriately once I shut and reopen the .sheet. Nonetheless, attempting to refresh it whereas the .sheet is open leads to a black display screen, regardless that the video URL has been up to date.

Conduct I noticed in the course of the replace:

  1. The VideoPlayer flashes however stays a black display screen after updating
    the URL.
  2. Closing and reopening the .sheet reveals the up to date video
  3. A number of makes an attempt to drive refresh the view or reinitialize AVPlayer did not work.

So my query is; How can I get VideoPlayer to refresh and show the brand new video instantly after the URL is up to date, with no need to shut and reopen the sheet?

The related code:

import SwiftUI
import AVKit

struct VideoPreviewView: View {
    @Binding var selectedVideoURL: URL?
    @State personal var participant: AVPlayer?

    var physique: some View {
        VStack {
            if let videoURL = selectedVideoURL {
                VideoPlayer(participant: participant)
                    .aspectRatio(9/16, contentMode: .match)
                    .onAppear {
                        participant = AVPlayer(url: videoURL)
            } else {
                Textual content("Video not accessible")
        .onChange(of: selectedVideoURL) { newURL in
            participant = newURL != nil ? AVPlayer(url: newURL!) : nil

// Utilization in ContentView
struct ContentView: View {
    @State personal var showVideoPreview: Bool = false
    @State personal var selectedVideoURL: URL? = URL(string: "https://instance.com/video.mp4")

    var physique: some View {
        // ... Your view setup ...

        .sheet(isPresented: $showVideoPreview) {
            VideoPreviewView(selectedVideoURL: $selectedVideoURL)

I’ve tried utilizing the .id modifier to drive the view to refresh.
Additionally tried reinitializing AVPlayer on URL change.
The problem persists throughout completely different video URLs and units.

Any steerage or various approaches to resolve this situation could be appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *