— SwiftUI, AppStorage, ObservableObject — 1 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.
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 SwiftUI2import Combine3
4class UserStore: ObservableObject {5 @Published var launchCount: Int = 06}
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' here3 @AppStorage("launchCount") var launchCount: Int = 04}
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@main2struct MyApp: App {3 @StateObject var userStore = UserStore()4
5 var body: some Scene {6 WindowGroup {7 ContentView()8 .onAppear {9 userStore.launchCount += 110 // Don't forget to change X to your desired count11 if userStore.launchCount % X == 0 {12 // Perform your action here13 }14 }15 .environmentObject(userStore)16 }17 }18}
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: UserStore3
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!