How do you use an alert to prompt for text in iOS with Swift?

ios, swift

Solution

You're getting a textfield as a string. Blammo.

Also, get the value in the handler.

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
            let textf = alert.textFields[0] as UITextField
            println(textf.text)
            }))

ps sometimes the error shown happens in a location different from the one given in the error message.

Problem

``` func addPitcher(sender: UIBarButtonItem) { var alert = UIAlertController(title: "New Pitcher", message: "Enter Name", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Finish", style: UIAlertActionStyle.Default, handler: nil)) alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in textField.placeholder = "Name" textField.secureTextEntry = false }) self.presentViewController(alert, animated: true, completion: nil) let newName : String = alert.textFields[0] as String println(newName) } ``` This is the function in which we try and create an alert to prompt for a name. We get "EXC_BAD_INSTRUCTION" error at the `alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in` line. How do we fix this error, or more importantly, how do we retrieve the text from the field? Thank you for all help.

Original source