swiftuialertviewuialertcontroller

Alert view with taking input password


In the following code, it is successfully implemented. Just need one modification. When the app initially opens the admin password should take a default password "Hello" and then when the user has access to the admin password, will edited and save it and then it will be in the key "admin password"

How can I make that default password possible on the first?

func enableSectionAlert() {
    let alertController = UIAlertController(title: "Admin Password", message: "Please input admin password", preferredStyle: .alert)

    let enable = UIAlertAction(title: "Enable", style: .default) { (_) in
        let field = alertController.textFields?[0].text
            if let x = UserDefaults.standard.string(forKey: "admin password"), x == field {

                self.demosSelectionEnabled()
                self.showSection.isUserInteractionEnabled = false
                self.showSection.textLabel?.textColor = UIColor.lightGray
            }
            else{

                let wrongPwd = UIAlertController(title: "Wrong Admin Password", message: nil, preferredStyle:UIAlertControllerStyle.alert)
                wrongPwd.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                self.present(wrongPwd, animated: true, completion: nil)


        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in
        textField.placeholder = "Admin Password"
        textField.isSecureTextEntry = true
    }

    alertController.addAction(enable)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)
}

}


Solution

  • I believe you want the default password to be "Hello", and have the option to change this later, and persist in userDefaults. If this is the case, why not initially set the default value as follows:

    UserDefaults.standard.set("Hello", forKey: "admin password")
    

    Set it just once in maybe AppDelegate, using the following method:

    private func setDefaultPassword() {
        if UserDefaults.standard.string(forKey: "admin password") == nil {
            UserDefaults.standard.set("Hello", forKey: "admin password")
        }
    }