1

I'm learning iOS development and I'm trying to view an alert to the user when they launch the app for the first time, then never again. So, I wrote this in my app delegate:

func applicationDidBecomeActive(_ application: UIApplication) {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .cancel, handler: nil))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)

This code works to view the alert, but the problem I've is that the alert is shown each time the app is launched. So can any one help? It would be extremely appreciated.

Jessica Kimble
  • 493
  • 2
  • 7
  • 17
  • 2
    You can use userdefault to store a boolean value. Then in your viewController you can check if the boolean is true or false. :) – Jacob Ahlberg Nov 05 '18 at 16:28

1 Answers1

3

You can use the UserDefaults class to store simple keys. For example, you could store a boolean that tells you if this is the first launch :

func isFirstLaunch() -> Bool {

    if (!UserDefaults.standard.bool(forKey: "launched_before")) {
        UserDefaults.standard.set(true, forKey: "launched_before")
        return true
    }
    return false
}

Then call this function and do the work you need in case it is the first launch :

if isFirstLaunch() {
   // Do something
}
Scaraux
  • 3,841
  • 4
  • 40
  • 80
  • Thank you for your answer, so I should put the alert code above inside the if isFirstLaunch() { Here } And currently this code is in app delegate. Is it okay to stay there or better to move it to ViewController? Thank you for anymore clarification! – Jessica Kimble Nov 05 '18 at 16:39
  • You can leave it here. It all depends what you want to do. You could also load your initial view controller (loading it from the code here, or set it as initial from a storyboard) and then immediatly show your alert inside. – Scaraux Nov 05 '18 at 17:09