Access input from UIAlertController

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.


I know comments have been posted to answer the question, but an answer should make the solution explicit.

@IBOutlet var newWordField: UITextField
func wordEntered(alert: UIAlertAction!){
    // store the new word
    self.textView2.text = deletedString + " " + self.newWordField.text
}
func addTextField(textField: UITextField!){
    // add the text field and make the result global
    textField.placeholder = "Definition"
    self.newWordField = textField
}

// display an alert
let newWordPrompt = UIAlertController(title: "Enter definition", message: "Trainging the machine!", preferredStyle: UIAlertControllerStyle.Alert)
newWordPrompt.addTextFieldWithConfigurationHandler(addTextField)
newWordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
newWordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: wordEntered))
presentViewController(newWordPrompt, animated: true, completion: nil)

This displays a prompt with a text field and two action buttons. It reads the text field when done.