DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


How to show a Popup alert on First Launch of an app in Swift UI?

  • 3 minutes read
  • 23 Views
How to show a Popup alert on First Launch of an app in Swift UI?

    Table of Contents

How to create a pop-up alert/ display alert in SwiftUI?

In this tutorial, we will learn to show/create a pop up alert on the first launch of Swift UI. I hope that you all know how to start a new project in Swift UI, if not, you can refer to this post to check out how to create a brand new project in Swift UI

First of all open the ‘ContentView.swift’ file in your editor. It will look like this:-

//  Created by Udit Vashisht on 18/01/22.
//

import SwiftUI

struct ContentView: View {

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In order to show the display alert, first of all we will need to wrap our text into a Vstack, so hold the command key and left click on the Text and then choose embed in VStack

embed-in-vstack-swiftui.png

Now just outside the view struct declare a State variable ‘showAlert’ and set it as true

@State var showAlert = true

Now just outside the VStack add the code to show your alert. The alert would have three components - title, message and dismissButton

import SwiftUI

struct ContentView: View {

    @State var showAlert = true

    var body: some View {

        VStack {
            Text("Hello, world!")
                .padding()
        }.alert(isPresented: $showAlert)
        {
            Alert(title: Text("Welcome"),
                  message: Text("Welcome to my App"),
                  dismissButton: .default(Text("Okay")))


        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

So, this will now show you the alert on the screen. But till now it will always show the alert as we have set showAlert as true and has never changed its value after the first launch.
alert-first-launch-swift-ui.png

So, to do so we will first change teh showAlert to false and then we will @AppStorage wrapper to store a boolean called ‘firstLaunch’ and after the very first launch we will change it’s value to false and thus the alert would not be shown in future. So the two lines of code would be as under:-

@State var showAlert = false
@AppStorage("firstLaunch") var firstLaunch: Bool = true

Then we will create a function which will see if it is the very first launch, if it is, the function will change the value of showAlert to true, thus showing the alert. And, at last it would change the value of firstLaunch to false, so that the function is not run thereafter.

func show(){
        if firstLaunch{
            showAlert = true
            firstLaunch = false
        }

Thereafter, we will add an onAppear modifier to the VStack and the complete code would look as under

import SwiftUI

struct ContentView: View {

    @State var showAlert = false
    @AppStorage("firstLaunch") var firstLaunch: Bool = true


    func show(){
        if firstLaunch{
            showAlert = true
            firstLaunch = false
        }

    }
    var body: some View {

        VStack {
            Text("Hello, world!")
                .padding()
        }.onAppear(perform: show)
            .alert(isPresented: $showAlert)
        {
            Alert(title: Text("Welcome"),
                  message: Text("Welcome to my App"),
                  dismissButton: .default(Text("Okay")))
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Posts

How to create a List View in Swift UI without using MVVM ? 2022
By Udit Vashisht

How to start a new iOS project in Xcode?

To create a new ios project, Open Xcode on your Mac and click on ‘Create a New Xcde Project’

create-a-new-xcode-project-swift-ui.png

In the next window, select ‘ios’ from the top menu and then select ‘App’ and click on Next

...

Read More
How to show an alert in SwiftUI?
By Udit Vashisht

How to show an alert in SwiftUI?

When we use SwiftUI, we can show alerts to the user with the alert() modifier. How that works depends on whether we want to target iOS 15 and later or iOS 13 and 14. I’ll show you both ways, but the newer iOS ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50