问题
My situation with this is different than every other example I have been able to find on here. I have a tab based app. On one of the tabs a user is able to press a button that downloads several files from a web server all at once.
I make use of NSOperation to perform each of these downloads so that I can utilize the built in dependencies. The downloads are all occurring on a background thread so the app remains responsive. When the final download is complete I put an alertController on screen letting the user know that they are complete.
If the user has selected a different tab when the alert controller is presented I get the warning: "Presenting view controllers on detached view controllers is discouraged"
If they are still on the same tab that started the downloads then I don't get the warning. I tried replacing:
[self presentViewController:alertController animated:YES completion:nil];
with
[self.view.window.rootViewController presentViewController:alertController animated:YES completion:nil];
but the result is that the alertController is never presented.
I am presenting the alertController on the main thread.
I have no way of predicting what tab view controller the user will be on when the downloads complete, and would really like to get rid of this warning.
I am developing on macOS and Xcode 8 with Obj-C.
回答1:
You need to delegate the result of the download to the top-level view controller, which sounds like your UITabBarController
. The UITabBarController
certainly knows which tab is selected, or it can present the alert on itself.
回答2:
Write to fix warning on presenting navigation controller or VC from current VC:
[self.view.window.rootViewController presentViewController:viewController animated:YES completion:nil];
To fix crash while dismissing view controller:
[self dismissViewControllerAnimated:YES completion:nil];
OR
If you present a view from a childViewController it will give you that warning. To avoid this, you can present a view on childViewController's parent.
[self.parentViewController presentViewController:viewController animated:YES completion:nil];
来源:https://stackoverflow.com/questions/40821786/warning-presenting-view-controllers-on-detached-view-controllers-is-discouraged