swift – SwiftUI VideoPlayer Not Refreshing with Updated URL on iOS


I’m running into an issue with SwiftUI’s VideoPlayer where it does not refresh when its binding URL is updated. The video only updates correctly when I close and reopen the .sheet. However, trying to refresh it while the .sheet is open results in a black screen, even though the video URL has been updated.

Behavior I observed during the update:

  1. The VideoPlayer flashes but remains a black screen after updating
    the URL.
  2. Closing and reopening the .sheet shows the updated video
    correctly.
  3. Several attempts to force refresh the view or reinitialize AVPlayer didn’t work.

So my question is; How can I get VideoPlayer to refresh and display the new video immediately after the URL is updated, without needing to close and reopen the sheet?

The relevant code:

import SwiftUI
import AVKit

struct VideoPreviewView: View {
    @Binding var selectedVideoURL: URL?
    @State private var player: AVPlayer?

    var body: some View {
        VStack {
            if let videoURL = selectedVideoURL {
                VideoPlayer(player: player)
                    .aspectRatio(9/16, contentMode: .fit)
                    .onAppear {
                        player = AVPlayer(url: videoURL)
                    }
            } else {
                Text("Video not available")
            }
        }
        .onChange(of: selectedVideoURL) { newURL in
            player = newURL != nil ? AVPlayer(url: newURL!) : nil
        }
    }
}

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

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

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

I’ve tried using the .id modifier to force the view to refresh.
Also attempted reinitializing AVPlayer on URL change.
The issue persists across different video URLs and devices.

Any guidance or alternative approaches to resolve this issue would be appreciated!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img