SwiftDeveloper SwiftDeveloper - 4 months ago 22
iOS Question

Getting text with UITextField Popup Alertview with Swift 3 fatal error

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 !

Answer

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 !!")
       let textField = alert.textFields?.first as! UITextField
       print("Item : \(textField.text))")
   }))
   self.present(alert, animated: true, completion: {
       print("completion block")
   })    
}
Comments