Search code examples
swiftibaction

Count user login attempts using IBAction button


I want to count how many times login button is clicked. If username and passwords field are empty and login button is clicked I want the count to be incremented by 1.

As I can not take "count" as inout parameter in this IBAction function, how can I accomplish this task?

@IBAction func loginButtonAction(_ sender: Any) {

    var count : Int = 0
    if (Username.text!.isEmpty || Password.text!.isEmpty ) {
        let myAlert = UIAlertController(title: "Alert", message: "All fields are required to fill in", preferredStyle: UIAlertController.Style.alert)
        let OkAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
        myAlert.addAction(OkAction)
        self.present(myAlert,animated: true, completion: nil)
        return
    }

Solution

  • YOU CAN USE STATIC VARIABLES:

    class MyLogs {
        static var numberOfLoginAttempts = 0
    
        init() {}
    
        func loginAttempt() {
            numberOfLoginAttempts += 1
        }
    
    }
    

    USAGE:

    let logs = MyLogs()

    @IBAction func loginButtonAction(_ sender: Any) {
    
        logs.loginAttempt()
        print("Login Attempt Number : \(MyLogs.numberOfLoginAttempts)")
        var count : Int = 0
        if (Username.text!.isEmpty || Password.text!.isEmpty ) {
            let myAlert = UIAlertController(title: "Alert", message: "All fields are required to fill in", preferredStyle: UIAlertController.Style.alert)
            let OkAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
            myAlert.addAction(OkAction)
            self.present(myAlert,animated: true, completion: nil)
            return
        }
    }
    

    If You Want To Close The Application And Still Have The Number Of Logins:

    Take a look at CoreData