1

I have popup alert and getting text with UITextField codes but when i want to get text string gives me nil error. my codes here. Im using Xcode latest and Swift 3.

 var tField: UITextField! @IBAction func addcommentButtonTapped(sender: AnyObject) { let alert = UIAlertController(title: "Write Comment", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField { (configurationTextField) in alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:self.handleCancel)) alert.addAction(UIAlertAction(title: "Send", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in print("Done !!") let textField = self.tField.text // HERE GIVES ERROR nil = tField if textField != nil { print("Item : \(textField))") } })) self.present(alert, animated: true, completion: { print("completion block") }) } } 

Error

fatal error: unexpectedly found nil while unwrapping an Optional value

Error line

let textField = self.tField.text // HERE GIVES ERROR nil = tField

Thank you !

1
  • Do you ever assign something to self.tField? Commented Jul 22, 2016 at 15:26

1 Answer 1

4

You have added your alert action inside the addTextField closure also you need to use first textField from array of textFields of the alertController so you need to change your code like this

@IBAction func addcommentButtonTapped(sender: AnyObject) { let alert = UIAlertController(title: "Write Comment", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:self.handleCancel)) alert.addTextField { (configurationTextField) in //configure here your textfield configurationTextField.textColor = UIColor.greenColor() } alert.addAction(UIAlertAction(title: "Send", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in print("Done !!") if let textField = alert.textFields?.first { print("Item : \(textField.text))") } })) self.present(alert, animated: true, completion: { print("completion block") }) } 
Sign up to request clarification or add additional context in comments.

4 Comments

Welcome mate Happy Coding :)
0 down vote Shouldn't it just be: let textField = alert.textFields?.first as downcasts from UITextField? only unwraps optionals?
@TaichiKato Edited the answer and also unwrapped the optional.
Thanks man, the code works well, I just wanted to let you know so people viewing this won't face the same issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.