l-spark l-spark - 11 days ago 5
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!

Answer

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")
        NSUserDefaults.standardUserDefaults().synchronize()
    } else {
        // user did not fill field
    }
}

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

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

alertController.addAction(confirmAction)
alertController.addAction(cancelAction)

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