Logo for tanaschita.com

How to manage lifecycle events in SwiftUI iOS applications

Discover SwiftUI's lifecycle events onAppear(), onDisappear() and task().

26 Sep 2022 · 3 min read

When working with views in an iOS application, we often need to trigger side effects when certain lifecycle events occur - for example loading or refreshing some data when a view appears.

In UIKit, we did that by overriding methods like viewDidAppear(_:) or viewDidDisappear(_:).

SwiftUI also provides methods like onAppear(perform:), onDisappear(perform:) and task(priority:_:) to react to lifecycle events. Let's jump in and look at those methods in more detail.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

The onAppear(perform:) method

The onAppear(perform:) method can be used to do some work right before the view appears - for example to setup some initial state.

struct SomeView: View {
var body: some View {
VStack {
...
}
.onAppear {
viewModel.update()
}
}
}

The onDisappear(perform:) method

The onDisappear(perform:) method can be used to do some work right after the view disappears - for example to cancel running tasks.

struct SomeView: View {
var body: some View {
VStack {
...
}
.onDisappear {
viewModel.cancelLoading()
}
}
}

The task(priority:_:) method

The task(priority:_:) method can be used to start some asynchronious work right before the view appears.

struct SomeView: View {
var body: some View {
VStack {
...
}
.task {
do {
try await viewModel.load()
} catch {
...
}
}
}
}

Additionally, SwiftUI automatically cancels the task when the view disappears.

The onReceive(_:perform:) method

Not a SwiftUI view lifecycle method per se, the onReceive(_:perform:) method can be useful to react to application lifecycle events - for example to update a view when the app enters foreground.

struct SomeView: View {
var body: some View {
VStack {
...
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
viewModel.update()
}
}
}
Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

widgetkit

swiftui

swift

ios

How to build a configurable widget with WidgetKit and SwiftUI

Learn how to allow users to customize their widgets.

05 Sep 2022 · 4 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum