How to display an Alert from a different class

Viewed 3389

I created a Utilities class to hold some common functions, one of which is an alertUser function that if called, will display an Alert box to the user with the provided title and message text. In another class file, I am validating some text field entries and if the validation doesn't pass, then I want to use the alertUser function from the Utilities class. However, when I do this, I get the following error message in the Xcode log:

Warning: Attempt to present <UIAlertController: 0x7f9c4be0b140> on <MyAppName.Utilities: 0x7f9c4be1cb60> whose view is not in the window hierarchy!

The calling code is in a UIViewController class file. Here's the code which is in the class ItemSettingsVC: UIViewController:

private func validateNameField() -> Bool {
    var passed = false

    if (nameField.hasText) {
        passed = true
    } else {
        Utilities().alertUser(strTitle: "Alert", strMessage: strInvalidNameFieldErrorMsg)
        passed = false
    }
    return passed
}

Here's the alertUser function which is in the class Utilities: UIViewController:

public func alertUser(strTitle: String, strMessage: String) {
    let myAlert = UIAlertController(title: strTitle, message: strMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}

This is running on iOS. I'm using Xcode 8 and swift 3. Any help is greatly appreciated. Thanks.

4 Answers
Related