Alert完成逻辑异常:弹出后无法切换ViewFinder问题排查
Hey there! Let's break down the most likely reasons your ViewFinder isn't appearing even though doSomething() is firing (and logging "TEST" as expected):
1. You're Trying to Present the ViewFinder While the Alert is Still Active
Alerts are modal presentations, and iOS won't allow you to stack another modal view directly on top of an active alert. The system will silently ignore the presentation request until the alert is dismissed.
Fix: Use the alert's completion handler (or the action's handler) to trigger the ViewFinder after the alert is gone. For example:
// When presenting your alert let alert = UIAlertController(title: "Notification", message: "Alert message here", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { [weak self] _ in // Trigger ViewFinder presentation ONLY after the alert is dismissed self?.doSomething() } alert.addAction(okAction) present(alert, animated: true)
2. UI Updates Aren't Happening on the Main Thread
All UI operations (like presenting view controllers) must run on the main thread. If doSomething() is being called from a background queue, your ViewFinder presentation will fail silently.
Fix: Wrap your ViewFinder presentation code in a DispatchQueue.main.async block:
func doSomething() { print("TEST") // Ensure UI work runs on main thread DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.present(self.viewFinderViewController, animated: true, completion: nil) } }
3. Your ViewFinder Isn't Configured/Presented Correctly
Double-check these details:
- Are you using
present(_:animated:completion:)to show the ViewFinder? If you're adding it as a subview, make sure it's added to the correct parent view (e.g.,view.windowor your root view controller's view) and has proper constraints/frame set. - Is the ViewFinder's view visible? Check if its
alphais set to 0, or if it has a transparent background that makes it hard to see. - For custom ViewFinder components: Did you initialize it correctly? (e.g., if using a XIB, did you load it with
init(nibName:bundle:)instead of justinit()?)
4. There's a Modal Presentation Conflict
If another modal view controller is already presented (before the alert), iOS might block the new presentation request. You can check for this and dismiss existing modals first:
func doSomething() { print("TEST") DispatchQueue.main.async { [weak self] in guard let self = self else { return } // Dismiss any existing presented VC first if let presentedVC = self.presentedViewController { presentedVC.dismiss(animated: false) { self.present(self.viewFinderViewController, animated: true) } } else { self.present(self.viewFinderViewController, animated: true) } } }
Start with checking the first two points—those are the most common culprits in this scenario!
内容的提问来源于stack exchange,提问作者Martin Vidic

