l-spark l-spark - 3 months ago 20
Swift Question

Swift: Insert Alert Box with Text Input (and Store Text Input )

In one of my view controllers, I want to make an alert box appear that prompts the user to type this information. I then want the user to store this input with NSUserDefaults. How can I go about doing this?

Thank you in advance!


Check this out:

let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .Alert)

let confirmAction = UIAlertAction(title: "Confirm", style: .Default) { (_) in
    if let field = alertController.textFields![0] as? UITextField {
        // store your data
        NSUserDefaults.standardUserDefaults().setObject(field.text, forKey: "userEmail")
    } else {
        // user did not fill field

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

alertController.addTextFieldWithConfigurationHandler { (textField) in
    textField.placeholder = "Email"


self.presentViewController(alertController, animated: true, completion: nil)