Created
April 8, 2025 16:40
-
-
Save jacobsapps/50c61bfa7221170897453fef7ecdc377 to your computer and use it in GitHub Desktop.
SwiftUI Lifecycle Listeners
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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