Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jacobsapps/50c61bfa7221170897453fef7ecdc377 to your computer and use it in GitHub Desktop.
Save jacobsapps/50c61bfa7221170897453fef7ecdc377 to your computer and use it in GitHub Desktop.
SwiftUI Lifecycle Listeners
@State private var videoCompleteTask: Task<Void, Error>?
@State private var showContinueButton: Bool = false
@State private var videoDurationRemaining: Double = 12
var body: some View {
// ...
.onAppear {
resetVideoCompleteTask()
}
.onDisappear {
videoCompleteTask?.cancel()
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
videoCompleteTask?.cancel()
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
resetVideoCompleteTask()
}
private func resetVideoCompleteTask() {
videoCompleteTask?.cancel()
videoCompleteTask = Task {
while !Task.isCancelled,
videoDurationRemaining > 0
{
try? await Task.sleep(for: .seconds(0.1))
videoDurationRemaining -= 0.1
if videoDurationRemaining <= 0 {
showContinueButton = true
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment