From 0c53420a7af306d629350e1244e8e2ccae08a312 Mon Sep 17 00:00:00 2001 From: abing Date: Wed, 4 Jan 2023 11:40:34 -0800 Subject: [PATCH] Fix RCTAlertController not showing when using SceneDelegate on iOS 13.0+ (#35716) Summary: On iOS 13.0+, app may use SceneDelegate for multiple windows support or CarPlay support. RCTAlertController can't find the correct root vc in such scene based apps. ## Changelog [iOS] [Fixed] - Fix RCTAlertController not showing when using SceneDelegate on iOS 13.0+. Pull Request resolved: https://github.com/facebook/react-native/pull/35716 Reviewed By: cipolleschi Differential Revision: D42253653 Pulled By: makovkastar fbshipit-source-id: ae4e833abca2af7af8028f3af9bd8d3f60ebd392 --- React/CoreModules/RCTAlertController.m | 32 +++++++++++++++++++++----- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/React/CoreModules/RCTAlertController.m b/React/CoreModules/RCTAlertController.m index 36730b4c05491d..3387a6e8d97c04 100644 --- a/React/CoreModules/RCTAlertController.m +++ b/React/CoreModules/RCTAlertController.m @@ -20,14 +20,21 @@ @implementation RCTAlertController - (UIWindow *)alertWindow { if (_alertWindow == nil) { - UIWindow *keyWindow = RCTSharedApplication().keyWindow; - if (keyWindow) { - _alertWindow = [[UIWindow alloc] initWithFrame:keyWindow.bounds]; + _alertWindow = [self getUIWindowFromScene]; + + if (_alertWindow == nil) { + UIWindow *keyWindow = RCTSharedApplication().keyWindow; + if (keyWindow) { + _alertWindow = [[UIWindow alloc] initWithFrame:keyWindow.bounds]; + } else { + // keyWindow is nil, so we cannot create and initialize _alertWindow + NSLog(@"Unable to create alert window: keyWindow is nil"); + } + } + + if (_alertWindow) { _alertWindow.rootViewController = [UIViewController new]; _alertWindow.windowLevel = UIWindowLevelAlert + 1; - } else { - // keyWindow is nil, so we cannot create and initialize _alertWindow - NSLog(@"Unable to create alert window: keyWindow is nil"); } } @@ -56,4 +63,17 @@ - (void)hide _alertWindow = nil; } +- (UIWindow *)getUIWindowFromScene +{ + if (@available(iOS 13.0, *)) { + for (UIScene *scene in RCTSharedApplication().connectedScenes) { + if (scene.activationState == UISceneActivationStateForegroundActive && + [scene isKindOfClass:[UIWindowScene class]]) { + return [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene]; + } + } + } + return nil; +} + @end