0
votes

I am trying to create and display an UIalert for my app. The problem with this alert is that I am trying to make and display an alert by writing the code in a class that is outside of the view controller. (Doing it in the class outside the view controller is important because of the other statements I have in the class UserApi pertaining to the profile image for which my alert is intended to be for.) Any idea on how to do this so I don't get the error

"Warning: Attempt to present <UIAlertController.....> : whose view is not in the window hierarchy!"?

I have already tried using UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true) instead of present(alertController, animated: true). I get the same error.

class UserApi : UIAlertController {

    func signUp()....

   //detect if user hasn't added a profile image and send an alert indicating the user must add a profile image
    guard let imageSelected = image else {

        let alertController = UIAlertController(title: "Profile Image Required", 
            message: "Please add a profile image to proceed." , preferredStyle: .alert)

        let OKAction = UIAlertAction(title: "OK", style: .default)
        alertController.addAction(OKAction)
        present(alertController, animated: true)

}
......
2

2 Answers

0
votes

In Guard let statement, return statement is required, Please replace the following code and retry. It is working fine.

   guard let imageSelected = image  else {
      let alertController = UIAlertController(title: "Profile Image Required",
                                              message: "Please add a profile image to proceed." , preferredStyle: .alert)

      let OKAction = UIAlertAction(title: "OK", style: .default)
      alertController.addAction(OKAction)
      present(alertController, animated: true)
      return
    }
0
votes

pass controller with signup function

like

func signUp(controller:UIViewController){
  let alertController = UIAlertController(title: "Profile Image Required", 
        message: "Please add a profile image to proceed." , preferredStyle: .alert)

    let OKAction = UIAlertAction(title: "OK", style: .default)
    alertController.addAction(OKAction)
    controller.present(alertController, animated: true)
}