lula08
lula08

Reputation: 215

SwiftUI: How can I display an alert on the very first start

I'm new in SwiftUI and I would like to show an alert when the user start the app for the first time. If the user opens the app a second (or third...) time, the alert should not come anymore.

struct ContentView: View {

    @State var alertShouldBeShown = true   
    
    var body: some View {
        VStack {
            Text("Hello World!")
            
            .alert(isPresented: $alertShouldBeShown, content: {

                Alert(title: Text("Headline"),
                      message: Text("Placeholder"),
                      dismissButton: Alert.Button.default(
                        Text("Accept"), action: {
                      }
                    )
                )
            })
        }
    }
}

Upvotes: 1

Views: 1673

Answers (1)

Asperi
Asperi

Reputation: 257493

Update: Xcode 13.4

Original variant is still valid and works "as-is", but now we can simplify code a bit with AppStorage

struct ContentView: View {
    @AppStorage("FirstStart") var alertShouldBeShown = true

    // ... same code

      dismissButton: Alert.Button.default(
        Text("Accept"), action: {
           alertShouldBeShown = false
      })

}

Original

Use UserDefaults to store state value.

Here is possible solution. Tested with Xcode 11.7/iOS 13.7

struct ContentView: View {

    @State var alertShouldBeShown = !UserDefaults.standard.bool(forKey: "FirstStart")

    var body: some View {
        VStack {
            Text("Hello World!")

            .alert(isPresented: $alertShouldBeShown, content: {

                Alert(title: Text("Headline"),
                      message: Text("Placeholder"),
                      dismissButton: Alert.Button.default(
                        Text("Accept"), action: {
                            UserDefaults.standard.set(true, forKey: "FirstStart")
                      }
                    )
                )
            })
        }
    }
}

Upvotes: 5

Related Questions