Skip to content
DeveloperMemos

Performing an Action Every X Launches in SwiftUI

SwiftUI, AppStorage, ObservableObject1 min read

In this blog post, we will explore how to perform an action every X launches of an app using SwiftUI. This can be useful in a variety of scenarios, such as showing a tutorial or asking for user feedback after a certain number of app uses. We will be using an ObservableObject called UserStore and @AppStorage for tracking launch counts.

Step 1: Creating the UserStore

First, we need to create an ObservableObject called UserStore. This will be used to track and update the launch count. Here's how we do it:

1import SwiftUI
2import Combine
3
4class UserStore: ObservableObject {
5 @Published var launchCount: Int = 0
6}

Step 2: Using @AppStorage

Next, we will use @AppStorage to persist the launch count across app launches. This allows us to keep track of the launch count even when the app is closed and reopene by automatically saving the changes to UserDefaults(so handy!). We update the UserStore class as follows:

1class UserStore: ObservableObject {
2 // You can change the key used to whatever you want, it's called 'launchCount' here
3 @AppStorage("launchCount") var launchCount: Int = 0
4}

Step 3: Incrementing the Launch Count

In our main App struct, we will increment the launch count each time the app launches. We will also check if the launch count is a multiple of X (replace X with your desired number). If it is, we will perform our desired action.

1@main
2struct MyApp: App {
3 @StateObject var userStore = UserStore()
4
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 .onAppear {
9 userStore.launchCount += 1
10 // Don't forget to change X to your desired count
11 if userStore.launchCount % X == 0 {
12 // Perform your action here
13 }
14 }
15 .environmentObject(userStore)
16 }
17 }
18}

Step 4: Using the Launch Count in Views

Finally, we can use the launch count from our UserStore in our views by injecting it as an environment object. This allows us to display the launch count or use it in other ways within our views.

1struct ContentView: View {
2 @EnvironmentObject var userStore: UserStore
3
4 var body: some View {
5 Text("App has been launched \(userStore.launchCount) times")
6 }
7}

And that's it! With these steps, you can perform an action every X launches of your SwiftUI app. This can be a powerful tool for enhancing user experience and engagement. Happy coding!