Amit Kalra
Amit Kalra

Reputation: 4113

Is there anyway to display UIAlertController ONLY when app launches?

so I have the following code in the viewDidAppear section

let theAlert = UIAlertController(title: "SUP", message: "DAWG", preferredStyle: UIAlertControllerStyle.Alert)
    theAlert.addAction(UIAlertAction(title: "sup!", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(theAlert, animated: true, completion: nil)

Don't mind the messages, I just came up with them randomly :3

Okay, so is there anyway for me to ONLY display this message when the app launches? Because when I come back from another controller, this message pops up again.

Upvotes: 1

Views: 456

Answers (1)

Chris Slowik
Chris Slowik

Reputation: 2879

Set a flag to indicate if the message has shown or not.

// first check to see if the flag is set
if alertShown == false {
    // show the alert
    alertShown = true
}

For this behavior to persist through launches, and show only on FIRST launch, save to NSUserDefaults.

// when your app loads, check the NSUserDefaults for your saved value
let userDefaults = NSUserDefaults.standardUserDefaults()
let alertShown = userDefaults.valueForKey("alertShown")
if alertShown == nil {
    // if the alertShown key is not found, no key has been set.
    // show the alert.
    userDefaults.setValue(true, forKey: "alertShown")
}

You can handle both of these in the root view controller viewDidLoad.

Upvotes: 3

Related Questions