I’m facing an issue in my SwiftUI app where a video preview inside a sheet flickers or flashes whenever a toast notification is shown or hidden after a video download. The video preview is part of a larger view, and the toast is intended to notify the user of the download status.
Here’s a simplified version of the relevant code:
import SwiftUI
import AVKit
struct VideoPreviewView: View {
// Simplified properties
@State private var showDownloadToast = false
@State private var isVideoURLValid: Bool? = nil
@State private var videoPlayer: AVPlayer?
var body: some View {
ZStack {
VStack {
// Wxisting layout
ScrollView {
if let isURLValid = isVideoURLValid, isURLValid {
VideoPlayer(player: videoPlayer)
.frame(height: 200) // Adjust size as needed
.onAppear {
if videoPlayer == nil {
videoPlayer = AVPlayer(url: yourVideoURL)
}
}
} else {
// Placeholder or loading view
}
}
.onAppear {
// Logic to check URL validity
}
}
if showDownloadToast {
ToastNotificationView(title: "Download Complete", isVisible: $showDownloadToast)
.zIndex(1)
.position(x: UIScreen.main.bounds.width / 2, y: 50)
}
}
}
private func downloadVideo() {
guard let url = videoURL else { return }
VideoDownloader().downloadVideoAndSaveToPhotos(from: url, progressHandler: nil) { success, error in
if success {
print("Download Successful")
withAnimation {
showDownloadToast = true
}
// Optionally, hide the toast after a delay
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation {
showDownloadToast = false
}
}
} else {
print("Download Failed: \(String(describing: error))")
}
}
}
// ToastNotificationView implementation
struct ToastNotificationView: View {
let title: String
@Binding var isVisible: Bool
var body: some View {
if isVisible {
Text(title)
.font(.system(size: 12))
.foregroundColor(.white)
.padding(EdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16))
.background(Color.blue.opacity(0.9))
.cornerRadius(10)
.shadow(radius: 10)
.transition(.asymmetric(
insertion: .move(edge: .top),
removal: .move(edge: .top)
))
.padding(.horizontal, 20)
// Use offset to adjust vertical position. Positive moves it downwards.
.offset(y: -10)
.onTapGesture {
withAnimation {
isVisible = false
}
}
}
}
}
I’ve tried various solutions, such as adjusting zIndex, changing animations, and even reworking the view hierarchy, but the flickering persists. This flickering happens only when the toast notification appears or disappears, and it’s especially noticeable due to the video playback.
How can I prevent the video preview from flickering in this scenario? Is there a SwiftUI-specific approach to handling state changes in a sheet without affecting the video playback?