HomeiOS Developmentswift - SwiftUI VideoPlayer Not Refreshing with Up to date URL on...

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


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

Habits I noticed through the replace:

  1. The VideoPlayer flashes however stays a black display screen after updating
    the URL.
  2. Closing and reopening the .sheet exhibits the up to date video
    appropriately.
  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, while not having 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 totally different video URLs and gadgets.

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments