带输入密码的警报视图

Alert view with taking input password

在下面的代码中,实现成功。只需要一个修改。当应用程序最初打开时,管理员密码应该采用默认密码 "Hello" 然后当用户可以访问管理员密码时,将编辑并保存它然后它将在密钥 "admin password"

我怎样才能使默认密码成为可能?

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)
}

}

您可以用这种方式初始化带有初始文本的文本字段

alertController.addTextField { (textField) in
    textField.text = "Hello"
    textField.isSecureTextEntry = true
}

如果我对你的理解是正确的,你希望密码 "Hello" 允许用户在安装应用程序后登录。他们登录后可以更改密码,对吗?

如果设置了键 admin password 的值,请在 AppDelegate 的 applicationDidLaunch 方法中存档此检查。 UserDefaults.standard.string returns nil 如果没有为此键设置值。如果您从此调用中获得 nil,只需将字符串设置为 Hello.

这允许用户使用 Hello 登录,直到更改用户默认设置中保存的密码。

我相信您希望默认密码为 "Hello",并且可以选择稍后更改它,并保留在 userDefaults 中。 如果是这种情况,为什么不最初设置默认值如下:

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

在 AppDelegate 中只设置一次,使用以下方法:

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