Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Swift: "Presenting view controllers on detached view controllers is discouraged"

As I continue to dive deeper into iOS development with Swift, I'm occasionally running into issues that are causing me grief. I ran into one this afternoon, and after doing some research on it, it seems that there are others who are running into it as well. So I thought I'd share the fix that worked for me.

The issue was a warning that was being thrown when running the app in the iOS Simulator. The warning read:

"Presenting view controllers on detached view controllers is discouraged…"

The warning was being displayed in Xcode when I would segue to a view controller in which a UIAlertController was being programmatically displayed.

The original code looked something like this:

override func viewDidLoad() {
	super.viewDidLoad()
	if plan.count == 0 {            
		let alertController = UIAlertController(title: "No Plan Available", message:
		"There is no plan associated with this record.", preferredStyle: UIAlertControllerStyle.Alert)
		alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
		   self.presentViewController(alertController, animated: true, completion: nil)
	}
}

Notice that I was trying to present the UIAlertController in the class's viewDidLoad function. And that's the problem. You see, at that point, the view has loaded, but it hasn't appeared yet. I believe that's why the warning is referring to a "detached view controller."

The solution that I found is to present the view controller not in the viewDidLoad function, but instead in the viewDidAppear function. At that point the view has loaded and is being displayed.

So the updated code looks like this:

override func viewDidAppear(animated: Bool) {
	if plan.count == 0 {            
		let alertController = UIAlertController(title: "No Plan Available", message:
		"There is no plan associated with this record.", preferredStyle: UIAlertControllerStyle.Alert)
		alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
		self.presentViewController(alertController, animated: true, completion: nil)
	}
}

I hope this helps others who run into the same issue.