From 30035266197e2f604159fcb391d4331904561997 Mon Sep 17 00:00:00 2001 From: abing Date: Wed, 5 Jun 2024 17:31:03 +0800 Subject: [PATCH] fix: properly get window scene to avoid crash on CarPlay app (#298) --- iOS/RCTOrientation/Orientation.m | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/iOS/RCTOrientation/Orientation.m b/iOS/RCTOrientation/Orientation.m index d93debf..f393219 100644 --- a/iOS/RCTOrientation/Orientation.m +++ b/iOS/RCTOrientation/Orientation.m @@ -60,8 +60,8 @@ - (UIInterfaceOrientation)getInterfaceOrientation { if(@available(iOS 13, *)) { UIInterfaceOrientation orientation = UIInterfaceOrientationUnknown; - UIScene *activeScene = [[UIApplication sharedApplication] connectedScenes].allObjects.firstObject; - if ([activeScene isKindOfClass:[UIWindowScene class]]) { + UIWindowScene *activeScene = [self getWindowScene]; + if (activeScene != nil && [activeScene isKindOfClass:[UIWindowScene class]]) { UIWindowScene *windowScene = (UIWindowScene *)activeScene; orientation = windowScene.interfaceOrientation; } @@ -111,6 +111,16 @@ - (void)deviceOrientationDidChange:(NSNotification *)notification } } +- (UIWindowScene *)getWindowScene { + NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects]; + for (id connectedScene in array) { + if ([connectedScene isKindOfClass:[UIWindowScene class]]) { + return connectedScene; + } + } + return nil; +} + - (NSString *)getOrientationStr: (UIInterfaceOrientation)orientation { NSString *orientationStr; @@ -154,17 +164,17 @@ - (void)lockToOrientation:(UIInterfaceOrientation) newOrientation usingMask:(UII [Orientation setOrientation:mask]; if (@available(iOS 16.0, *)) { - UIWindowScene *windowScene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject; - - UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:mask]; - [windowScene requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) { + UIWindowScene *windowScene = [self getWindowScene]; + if (windowScene != nil) { + UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:mask]; + [windowScene requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) { #if DEBUG - if (error) { - NSLog(@"Failed to update geometry with UIInterfaceOrientationMask: %@", error); - } + if (error) { + NSLog(@"Failed to update geometry with UIInterfaceOrientationMask: %@", error); + } #endif - }]; - + }]; + } } else { UIDevice* currentDevice = [UIDevice currentDevice];