Access input from UIAlertController

Andrew picture Andrew · Jun 11, 2014 · Viewed 34.7k times · Source

I've got a UIAlertController which is prompted to the user when they choose "Enter Password" on the TouchID screen. How do I recover the user's input after presenting this on screen?

let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert)
passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
                        textField.placeholder = "Password"
                        textField.secureTextEntry = true
                        })

presentViewController(passwordPrompt, animated: true, completion: nil)

I know the OK button should probably have a handler, but right now this code doesn't really do anything, but I want to display the output of the text field through a println. This is really just a test app for me to learn Swift and some new API stuff.

Answer

Ash Furrow picture Ash Furrow · Sep 7, 2014

I've written up a blog post exploring the new API. You can just capture a local variable in the closure and you're good to go.

var inputTextField: UITextField?
let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your password.", preferredStyle: UIAlertControllerStyle.Alert)
passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
    // Now do whatever you want with inputTextField (remember to unwrap the optional)
}))
passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
    textField.placeholder = "Password"
    textField.secureTextEntry = true
    inputTextField = textField
 })

presentViewController(passwordPrompt, animated: true, completion: nil)

That way you avoid having an unnecessary property on your view controller.