1

I want to show an alert textfield only when the app is first installed and the first time it runs.

Where should I write any code?

Rizwan
  • 3,324
  • 3
  • 17
  • 38
dinggu
  • 111
  • 7
  • 1
    What should happen second time onwards? – Bappaditya Dec 13 '18 at 06:00
  • 2
    it is simple so not posting as answer . Keep Bool in user defaults and toggle it when you show it – Prashant Tukadiya Dec 13 '18 at 06:00
  • First you need to know if is the first time the app was installed/launched, for that refer to this one https://stackoverflow.com/questions/27208103/detect-first-launch-of-ios-app and from there, on your first viewController display the alert – rgkobashi Dec 13 '18 at 06:00
  • In appdelegagte write the code store a variable inside persistent storage if alert is shown it so simple – Vinodh Dec 13 '18 at 06:01

1 Answers1

4

Store the information (may be a Bool Flag) in NSUserDefaults that whether Alert is shown or not. If not shown then show and set the value accordingly in NSUserDefaults

let isInfoShown = UserDefaults.standard.string(forKey: "Info")
if (isInfoShown == nil || isInfoShown == "")
{
    UserDefaults.standard.setValue("ShownInfo", forKey: "Info")
    // Show Alert  here
}

When handled With Bool in UserDefaults

let alertShown = UserDefaults.standard.bool(forKey: "ShownAlert")
if !alertShown {
    print("1st time launch, showing info Alert.")
    UserDefaults.standard.set(true, forKey: "ShownAlert")
}

Note - UserDefaults.standard.bool(forKey: "ShownAlert"), won't return nil, but false if the value doesn't exist.

SideNote - If App is removed/deleted and re-installed then Alert will show again. If App is updated then Alert will not be shown. This is because UserDefaults is lost when App is deleted.

Rizwan
  • 3,324
  • 3
  • 17
  • 38
  • Thanks for the kind explanation. Can I write the above code in AppDelegate? – dinggu Dec 13 '18 at 06:14
  • You may just wrap over this code where Alert is being shown. //Show Alert here - just put your alert here. If the Alert is in AppDelegate itself, yes you can put it there. – Rizwan Dec 13 '18 at 06:21
  • I understand. Thank you very much! – dinggu Dec 13 '18 at 06:22