0

I have a terms agreement that needs to pop up only once, however it is popping up each time the app is launched, how can I make it only pop up one time and when pressed agreed to never pop up again unless app is deleted and redownloaded. I am trying to follow How can I show a view on the first launch only?

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        if !UserDefaults.standard.bool(forKey: "Walkthrough") {
            UserDefaults.standard.set(false, forKey: "Walkthrough")
        }
    }

}

class FirstViewController: UIViewController, UIAlertViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        if UserDefaults.standard.bool(forKey: "Walkthrough") {
            print("already shown")
            // Terms have been accepted, proceed as normal
        } else {
            agree()
        }
    }

}

my agree function is an alert controller

Matt Zanchelli
  • 357
  • 1
  • 12
user8000557
  • 137
  • 8

2 Answers2

0

i forgot to add after agree()

UserDefaults.standard.set(true, forKey: "Walkthrough")
user8000557
  • 137
  • 8
0

Just save a bool in UserDefaults with the answer if agreed or not and check if the key "WalkThrough" exists or not. If not you will show him the alert if found do nothing.

Add this to the initial viewController in viewDidAppear method:

    let alert = UIAlertController(title: "Message", message: "You need to agree to terms and conditions", preferredStyle: .alert)
    let action = UIAlertAction(title: "Not Agreed", style: .default) { (action) in

        UserDefaults.standard.set(false, forKey: "WalkThrough")

        alert.dismiss(animated: true, completion: nil)
    }
    let action2 = UIAlertAction(title: "Agreed", style: .default) { (action) in

        UserDefaults.standard.set(true, forKey: "WalkThrough")

        alert.dismiss(animated: true, completion: nil)
    }

    alert.addAction(action)
    alert.addAction(action2)


    if (UserDefaults.standard.object(forKey: "WalkThrough") == nil) {
        //show alert and save answer
        self.present(alert, animated: true, completion: nil)

    }
Kegham K.
  • 1,589
  • 22
  • 40