简体   繁体   English

如何将在UITextField中输入的字符串保存到NSUserDefaults Swift

[英]How to save string entered in UITextField to NSUserDefaults Swift

I am creating an app in which i want the user to create their password the first time they open the app. 我正在创建一个应用程序,希望用户在首次打开该应用程序时创建其密码。 I have an alert pop up that has a textfield and a button I want to save whatever text they enter into the textfield for use later. 我弹出一个警报,其中有一个文本字段和一个按钮,我想保存他们输入到文本字段中的任何文本以供以后使用。 Here is the code for the alert I have so far. 这是到目前为止的警报代码。

override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated);    //You should call super.

    let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
    if firstLaunch  {
        println("Not first launch.")
    }
    else {
        println("First launch, setting NSUserDefault.")
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
        var alert = UIAlertController(title: "Create Your Password", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Save Password", style: UIAlertActionStyle.Default, handler: nil))
        alert.addTextFieldWithConfigurationHandler({
            textfield in
            textfield.placeholder = "Password"
            textfield.secureTextEntry = true
        })
}

I have no clue where to start for this, and any help would be aprecciated. 我不知道从哪里开始,任何帮助将不胜感激。

Textfield that you are using is limited within the scope of closure. 您使用的文本字段仅限于闭包范围。 Say I enter password as 12345. Which you can check by checking text property of textfield within closure. 假设我输入的密码为12345。您可以通过检查闭包内textfield的text属性来进行检查。 But you can't access those properties outside the closure. 但是您不能在闭包之外访问这些属性。

Coming back to question. 回到问题。 Please change your code like below 请像下面那样更改您的代码

alert.addAction(UIAlertAction(title: "Save Password", style:   UIAlertActionStyle.Default)){ (action) in

//set password.
UserDefaults.standard.setValue("12345", forKey: "Password")
}


//Note that password i.e. 12345 is stored as of type Any?. After getting it back from defaults you will have to cast in back to string.

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM