警告:尝试呈现 <UIAlertController: > > 其视图不在 window 层次结构中

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

我正在尝试为我的应用程序创建并显示一个 UIalert。警报在视图控制器内部,它将在 api 服务调用内部调用,如下所示。

    APIService().loginr(success: { result in
        print(result!)
        let json = result as! NSDictionary
        self.showResponseAlert(title: "Success!", message: json["message"] as? String)

    }, failure: {error in
        print(error!)
    }, parameters: parameters)

和我的 uiAlert

func showResponseAlert(title:String?,message:String?){
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    self.present(alert, animated: true, completion: nil)
}

我也试过了

   DispatchQueue.main.async{
       self.present(alertController, animated: true, completion: nil)
   }

但对我不起作用。

用它来显示警报。

func showResponseAlert(title:String?,message:String?){
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    if var topController = UIApplication.shared.keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            topController.present(alert, animated: true, completion: nil)
     }
}