In the following code the alert appears when I tap the alert button. The alert for missing data (bales == 0) from a text field on the same view controller as the button, does not appear.
I think this is a problem with the self.present. Self does not appear to be correct abter the checkData() fuunc is called. How do I fix this?
The error I get is
Warning: Attempt to present <UIAlertController: 0x7fc5bd801400> on <Alert_test.ViewController: 0x7fc5bad122a0> whose view is not in the window hierarchy!
TIA
Russ
import UIKit
class ViewController: UIViewController {
@IBAction func showAlert(_ sender: Any) {
showAlert1()//this shows alert
}
@IBOutlet weak var bales: UITextField!
func showAlert1() {
let alert = UIAlertController(title: "OOPS", message: "There is a problem with your data entry.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("FIX", comment: "Default action"), style: .default, handler: { _ in
NSLog("The \"FIX\" alert occured.")
}))
self.present(alert, animated: true, completion: nil)
}
func checkData() {
if bales.text == "" {
showAlert1() //this does not show alert when bales = ""
}}
override func viewDidLoad() {
super.viewDidLoad()
checkData()
}
Found the problem the alert was not displaying because swift did not wait for it to display and continued to run code which at one point included a segue to another view controller which then crashed because the bad data the alert was supposed to warn about was not fixed.
I fixed that by including
DispatchQueue.main.asyncAfter(deadline: .now() + 5)
and only allowing the code to continue if a problem was found by use of else when the missing data check was triggered.