2017-05-08 65 views
2

在以下代码中,它已成功实施。只需要一个修改。当应用程序最初打开管理员密码时,应该使用默认密码“Hello”,然后当用户有权访问管理员密码时,将编辑并保存它,然后它将在密钥“管理员密码”带输入密码的警报视图

如何我可以在第一次使用默认密码吗?

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

}

回答

3

我相信你要的默认密码是“你好”,并有选择稍后改变它,并坚持在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") 
    } 
} 
+0

所以我只是把下面的行代码在我的AppDelegate和多数民众赞成它? UserDefaults.standard.set(“Hico1234”,forKey:“管理员密码”) – habed

+0

函数setDefaultPassword是否需要从我的enableSectionAlert中调用,或者一旦应用程序运行并且管理员密码键是空的,它将接受输入你好? – habed

+1

我想只是从AppDelegate中的appDidFinishLaunchingWithOptions()调用它,那应该没问题。 –

0

可以初始化初始文本文本框这样

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

如果我正确理解你你想要的密码“你好”允许用户安装后登录应用程序。一旦他们登录后,他们可以更改密码,对吧?

如果设置了密钥admin password的值,请将此检查存档在AppDelegate的applicationDidLaunch方法中。如果没有为此密钥设置值,则返回nil。如果您从此调用中获得nil,请将字符串设置为Hello

这允许用户使用Hello登录,直到保存用户默认值的密码更改为止。