UialertController to show only once when the var hits an certain Value

217 views Asked by At

so the way my app works is you tap on a cell , a var value gets modified (+1 for example). I've figured out how to get a UIalert to pop when my var reaches a certain value (10). But now everytime I update the var the alert pops. What i would like it to do is to pop when the var hits 10 and stop after that

Heres the code :

    if (section1score >= 10){
        let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
            message: " \(message1)",
            preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) {
            action -> Void in }

        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)

    } 

if (section2score >= 10){
        let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
            message: "\(message2)",
            preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) {
            action -> Void in }

        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)

    }
2

There are 2 answers

2
Daniel Storm On BEST ANSWER

Setup a Bool to check if the alert has been shown or not. Create the Bool globally and set it to false initially.

var showedAlert = false

func yourFunction() {
    if section1score >= 10 && showedAlert == false {
        // show alert
        showedAlert = true
    }

    if section2score >= 10 && showedAlert == false {
        // show alert
        showedAlert = true
    }
}

Comparison Operators

3
keithbhunter On

You could use a property to keep track of when you show the alert so that once you show it, you won't show it again.

var hasShownAlert: Bool = false

if (section1score >= 10 && !hasShownAlert){
    let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
        message: " \(message1)",
        preferredStyle: .Alert)

    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        action -> Void in }

    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
    hasShownAlert = true
} 

if (section2score >= 10 && !hasShownAlert){
    let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
        message: "\(message2)",
        preferredStyle: .Alert)

    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        action -> Void in }

    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
    hasShownAlert = true
}