视图Dismiss操作未触发Completion函数,寻求技术解决方案
Hey there! Let's break down why that completion block in your dismiss call never runs, and how to fix it.
The Root Problem
Looking at your code:
@IBAction func tapBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: { print("this should print") }) }
You're calling both popViewController and dismiss in the same action. Here's what happens:
popViewControllerremoves your current view controller from the navigation stack immediately (or as part of the animated transition).- By the time you call
dismiss, your view controller is no longer part of the active view hierarchy—so thedismissoperation doesn't execute at all, which means its completion block never gets triggered.
Wrapping it in DispatchQueue.main.async doesn't help because the issue isn't about thread timing—it's about your view controller already being discarded when dismiss tries to run.
The Fixes
You need to pick the right method based on how your view controller was presented:
1. If your view controller was pushed onto the navigation stack
Use only popViewController. For iOS 16+, Apple added a completion handler directly to popViewController:
@IBAction func tapBack(_ sender: Any) { if #available(iOS 16.0, *) { navigationController?.popViewController(animated: true) { print("this should print") } } else { // For iOS versions before 16, use UINavigationControllerDelegate navigationController?.popViewController(animated: true) // Implement navigationController(_:didShow:animated:) in your delegate to detect when pop finishes } }
2. If your view controller was presented modally
Use only dismiss—you don't need the popViewController call at all:
@IBAction func tapBack(_ sender: Any) { dismiss(animated: true) { print("this should print") } }
Key Takeaway
Never mix popViewController and dismiss for the same view controller. Each method corresponds to a different way of presenting view controllers:
push↔popViewControllerpresent↔dismiss
内容的提问来源于stack exchange,提问作者Andrew WC Brown

