How To Fix Warning Attempt To Present UIAlertController On ViewController Whose View Is Not In The Window Hierarchy

I want to implement an effect that when the iOS app start, it popup an alert dialog in the screen and display some messages. But during the process, i meet an error message like below, and the alert dialog is not displayed as i want. This article will tell you how to fix this issue.

1. Error Message.

TestProject[2673:43682] Warning: Attempt to present <UIAlertController: 0x7f8ae603c000> on <TestProject.ViewController: 0x7f8ae5d097d0> whose view is not in the window hierarchy!

2. How To Fix Above Error.

The reason for this error is because i create the instance of swift UIAlertController class in the ViewController class’s viewDidLoad() method.

To fix this error, i need to override ViewController class’s viewDidAppear method and put the UIAlertController class initialization code in the viewDidAppear method like below.


//  ViewController.swift
//  TestProject
//  Created by song zhao on 8/6/19.
//  Copyright © 2019 All rights reserved.

import UIKit

class ViewController: UIViewController {
    var message:String = ""

    override func viewDidLoad() {
        message = "Hello Swift"

    /* Override the viewDidAppear method and display iOS swift alert popup dialog in it. */
    override func viewDidAppear(_ animated: Bool) {

        /* Below method will display a swift alert dialog window. */
    /* Below function will create an iOS swift alert dialog and display the message in it. */
    func presentAlertDialog() -> Void{

        /* Create a UIAlertController object with provided title, message and alert dialog style. */
        let alertController:UIAlertController = UIAlertController(title: "Message", message: message, preferredStyle: UIAlertController.Style.alert)

        /* Create a UIAlertAction object with title to implement the alert dialog OK button. */    
        let alertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:nil)
        /* Add above UIAlertAction button to the UIAlertController object. */        

        /* Display the swift alert dialog window. */
        present(alertController, animated: true, completion: nil)


Below is the screen when execute above app.

popup an alert dialog when ios swift app start


  1. How To Prompt Alert Dialog When Click A Button In Swift
0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x