I want to implement an effect that when the iOS app starts, it popup an alert dialog on the screen and displays 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.
- Below is the 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 the 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
// // ViewController.swift // TestProject // // Copyright © 2019 dev2qa.com. All rights reserved. // import UIKit class ViewController: UIViewController { var message:String = "" override func viewDidLoad() { super.viewDidLoad() message = "Hello Swift" print(message) } /* 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. */ presentAlertDialog() } /* 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. */ alertController.addAction(alertAction) /* Display the swift alert dialog window. */ present(alertController, animated: true, completion: nil) } }
- Below is the screen when executing the above app.
Reference