Coder Coder - 6 months ago 23
Swift Question

UiAlertView or UiAlertController to display only once in Swift

How can I get my

UiAlertController
or
UIAlertView
to display only once in Swift?

override func viewDidLoad() {

var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

if let nameIsNotNill = defaults.objectForKey("name") as? String {
self.name.text = defaults.objectForKey("name") as String
}

if let phoneIsNotNill = defaults.objectForKey("phone") as? String {
self.phone.text = defaults.objectForKey("phone") as String
}

var alert = UIAlertController(title: "Disclaimer", message: "WE STRIVES TO PROVIDE ACCURATE, UP-TO-DATE INFORMATION ON THIS APPS.", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Disagree", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)

super.viewDidLoad()

}

Answer

Declare a global Bool variable just under import commands:

var justOnce:Bool = true

You should use it this way:

override func viewDidLoad() {
    super.viewDidLoad()
    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

    if let nameIsNotNill = defaults.objectForKey("name") as? String {
        name.text = defaults.objectForKey("name") as String
    }

    if let phoneIsNotNill = defaults.objectForKey("phone") as? String {
         phone.text = defaults.objectForKey("phone") as String
    }

    if justOnce {
       var alert = UIAlertController(title: "Disclaimer", message: "WE STRIVES TO PROVIDE ACCURATE, UP-TO-DATE INFORMATION ON THIS APPS.", preferredStyle: UIAlertControllerStyle.Alert)
       alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "Disagree", style: UIAlertActionStyle.Default, handler: nil))
       self.presentViewController(alert, animated: true, completion: nil)

        justOnce = false
    }
}