Benpeterscode
Benpeterscode

Reputation: 93

How To Make an Alert Only Appear Once

I'm trying to figure out is how to create a pop up window that only appears once when you start the app and then won't appear again unless you close the app and reboot it. However, if you view the code below, you will realize that the alert will pop up every time the ViewController appears. For example, if you go to the settings tab and then return to the main ViewController, then the alert will pop up.

override func viewDidAppear(animated: Bool) {
    let alertController = UIAlertController(title: "Disclaimer", message: "WARNING: Please ride carefully!", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
}

Upvotes: 3

Views: 3361

Answers (1)

rmickeyd
rmickeyd

Reputation: 1551

Just create a global variable that is a Bool. If the app is opened it starts at false. Then once the disclaimer is seen it sets the variable to true. Then present the View Controller based on the value of the variable.

    var disclaimerHasBeenDisplayed = false

class ViewController {

     override func viewDidAppear(animated: Bool) {

          if disclaimerHasBeenDisplayed == false {

             disclaimerHasBeenDisplayed = true

             let alertController = UIAlertController(title: "Disclaimer", message: "WARNING: Wakeboarding is fun, however it can be highly dangerous.
     Wake Dice is not liable for any injuries obtained while wakeboarding. Please ride carefully!", preferredStyle: UIAlertControllerStyle.Alert)
     alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default,handler: nil))

        self.presentViewController(alertController, animated: true, completion: nil)
    }
    }
    }

Upvotes: 8

Related Questions