1// Copyright 2015-present 650 Industries. All rights reserved. 2 3@import UIKit; 4 5#import "EXAnalytics.h" 6#import "EXAppLoader.h" 7#import "EXAppViewController.h" 8#import "EXAppLoadingProgressWindowController.h" 9#import "EXAppLoadingCancelView.h" 10#import "EXManagedAppSplashScreenViewProvider.h" 11#import "EXManagedAppSplashScreenConfigurationBuilder.h" 12#import "EXManagedAppSplashScreenViewController.h" 13#import "EXHomeAppSplashScreenViewProvider.h" 14#import "EXEnvironment.h" 15#import "EXErrorRecoveryManager.h" 16#import "EXErrorView.h" 17#import "EXFileDownloader.h" 18#import "EXKernel.h" 19#import "EXKernelUtil.h" 20#import "EXReactAppManager.h" 21#import "EXVersions.h" 22#import "EXUpdatesManager.h" 23#import "EXUtil.h" 24 25#import <EXSplashScreen/EXSplashScreenService.h> 26#import <React/RCTUtils.h> 27#import <ExpoModulesCore/EXModuleRegistryProvider.h> 28 29#if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 30#import <EXScreenOrientation/EXScreenOrientationRegistry.h> 31#endif 32 33#import <React/RCTAppearance.h> 34#if defined(INCLUDES_VERSIONED_CODE) && __has_include(<ABI46_0_0React/ABI46_0_0RCTAppearance.h>) 35#import <ABI46_0_0React/ABI46_0_0RCTAppearance.h> 36#endif 37#if defined(INCLUDES_VERSIONED_CODE) && __has_include(<ABI45_0_0React/ABI45_0_0RCTAppearance.h>) 38#import <ABI45_0_0React/ABI45_0_0RCTAppearance.h> 39#endif 40 41#define EX_INTERFACE_ORIENTATION_USE_MANIFEST 0 42 43// when we encounter an error and auto-refresh, we may actually see a series of errors. 44// we only want to trigger refresh once, so we debounce refresh on a timer. 45const CGFloat kEXAutoReloadDebounceSeconds = 0.1; 46 47// in development only, some errors can happen before we even start loading 48// (e.g. certain packager errors, such as an invalid bundle url) 49// and we want to make sure not to cover the error with a loading view or other chrome. 50const CGFloat kEXDevelopmentErrorCoolDownSeconds = 0.1; 51 52// copy of RNScreens protocol 53@protocol EXKernelRNSScreenWindowTraits 54 55+ (BOOL)shouldAskScreensForScreenOrientationInViewController:(UIViewController *)vc; 56 57@end 58 59NS_ASSUME_NONNULL_BEGIN 60 61@interface EXAppViewController () 62 <EXReactAppManagerUIDelegate, EXAppLoaderDelegate, EXErrorViewDelegate, EXAppLoadingCancelViewDelegate> 63 64@property (nonatomic, assign) BOOL isLoading; 65@property (atomic, assign) BOOL isBridgeAlreadyLoading; 66@property (nonatomic, weak) EXKernelAppRecord *appRecord; 67@property (nonatomic, strong) EXErrorView *errorView; 68@property (nonatomic, strong) NSTimer *tmrAutoReloadDebounce; 69@property (nonatomic, strong) NSDate *dtmLastFatalErrorShown; 70@property (nonatomic, strong) NSMutableArray<UIViewController *> *backgroundedControllers; 71 72@property (nonatomic, assign) BOOL isStandalone; 73@property (nonatomic, assign) BOOL isHomeApp; 74 75/* 76 * Controller for handling all messages from bundler/fetcher. 77 * It shows another UIWindow with text and percentage progress. 78 * Enabled only in managed workflow or home when in development mode. 79 * It should appear once manifest is fetched. 80 */ 81@property (nonatomic, strong, nonnull) EXAppLoadingProgressWindowController *appLoadingProgressWindowController; 82 83/** 84 * SplashScreenViewProvider that is used only in managed workflow app. 85 * Managed app does not need any specific SplashScreenViewProvider as it uses generic one povided by the SplashScreen module. 86 * See also EXHomeAppSplashScreenViewProvider in self.viewDidLoad 87 */ 88@property (nonatomic, strong, nullable) EXManagedAppSplashScreenViewProvider *managedAppSplashScreenViewProvider; 89@property (nonatomic, strong, nullable) EXManagedAppSplashScreenViewController *managedSplashScreenController; 90 91/* 92 * This view is available in managed apps run in Expo Go only. 93 * It is shown only before any managed app manifest is delivered by the app loader. 94 */ 95@property (nonatomic, strong, nullable) EXAppLoadingCancelView *appLoadingCancelView; 96 97@end 98 99@implementation EXAppViewController 100 101#pragma mark - Lifecycle 102 103- (instancetype)initWithAppRecord:(EXKernelAppRecord *)record 104{ 105 if (self = [super init]) { 106 _appRecord = record; 107 _isStandalone = [EXEnvironment sharedEnvironment].isDetached; 108 } 109 return self; 110} 111 112- (void)dealloc 113{ 114 [self _invalidateRecoveryTimer]; 115 [[NSNotificationCenter defaultCenter] removeObserver:self]; 116} 117 118- (void)viewDidLoad 119{ 120 [super viewDidLoad]; 121 122 // EXKernel.appRegistry.homeAppRecord does not contain any homeAppRecord until this point, 123 // therefore we cannot move this property initialization to the constructor/initializer 124 _isHomeApp = _appRecord == [EXKernel sharedInstance].appRegistry.homeAppRecord; 125 126 // show LoadingCancelView in managed apps only 127 if (!self.isStandalone && !self.isHomeApp) { 128 self.appLoadingCancelView = [EXAppLoadingCancelView new]; 129 // if home app is available then LoadingCancelView can show `go to home` button 130 if ([EXKernel sharedInstance].appRegistry.homeAppRecord) { 131 self.appLoadingCancelView.delegate = self; 132 } 133 [self.view addSubview:self.appLoadingCancelView]; 134 [self.view bringSubviewToFront:self.appLoadingCancelView]; 135 } 136 137 // show LoadingProgressWindow in the development client for all apps other than production home 138 BOOL isProductionHomeApp = self.isHomeApp && ![EXEnvironment sharedEnvironment].isDebugXCodeScheme; 139 self.appLoadingProgressWindowController = [[EXAppLoadingProgressWindowController alloc] initWithEnabled:!self.isStandalone && !isProductionHomeApp]; 140 141 // show SplashScreen in standalone apps and home app only 142 // SplashScreen for managed is shown once the manifest is available 143 if (self.isHomeApp) { 144 EXHomeAppSplashScreenViewProvider *homeAppSplashScreenViewProvider = [EXHomeAppSplashScreenViewProvider new]; 145 [self _showSplashScreenWithProvider:homeAppSplashScreenViewProvider]; 146 } else if (self.isStandalone) { 147 [self _showSplashScreenWithProvider:[EXSplashScreenViewNativeProvider new]]; 148 } 149 150 self.view.backgroundColor = [UIColor whiteColor]; 151 _appRecord.appManager.delegate = self; 152 self.isLoading = YES; 153} 154 155- (void)viewDidAppear:(BOOL)animated 156{ 157 [super viewDidAppear:animated]; 158 if (_appRecord && _appRecord.status == kEXKernelAppRecordStatusNew) { 159 _appRecord.appLoader.delegate = self; 160 _appRecord.appLoader.dataSource = _appRecord.appManager; 161 [self refresh]; 162 } 163} 164 165- (BOOL)shouldAutorotate 166{ 167 return YES; 168} 169 170- (void)viewWillLayoutSubviews 171{ 172 [super viewWillLayoutSubviews]; 173 if (_appLoadingCancelView) { 174 _appLoadingCancelView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 175 } 176 if (_contentView) { 177 _contentView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 178 } 179} 180 181- (void)viewWillDisappear:(BOOL)animated 182{ 183 [_appLoadingProgressWindowController hide]; 184 [super viewWillDisappear:animated]; 185} 186 187/** 188 * Force presented view controllers to use the same user interface style. 189 */ 190- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion 191{ 192 [super presentViewController:viewControllerToPresent animated:flag completion:completion]; 193 [self _overrideUserInterfaceStyleOf:viewControllerToPresent]; 194} 195 196/** 197 * Force child view controllers to use the same user interface style. 198 */ 199- (void)addChildViewController:(UIViewController *)childController 200{ 201 [super addChildViewController:childController]; 202 [self _overrideUserInterfaceStyleOf:childController]; 203} 204 205#pragma mark - Public 206 207- (void)maybeShowError:(NSError *)error 208{ 209 self.isLoading = NO; 210 if ([self _willAutoRecoverFromError:error]) { 211 return; 212 } 213 if (error && ![error isKindOfClass:[NSError class]]) { 214#if DEBUG 215 NSAssert(NO, @"AppViewController error handler was called on an object that isn't an NSError"); 216#endif 217 return; 218 } 219 220 // we don't ever want to show any Expo UI in a production standalone app, so hard crash 221 if ([EXEnvironment sharedEnvironment].isDetached && ![_appRecord.appManager enablesDeveloperTools]) { 222 NSException *e = [NSException exceptionWithName:@"ExpoFatalError" 223 reason:[NSString stringWithFormat:@"Expo encountered a fatal error: %@", [error localizedDescription]] 224 userInfo:@{NSUnderlyingErrorKey: error}]; 225 @throw e; 226 } 227 228 NSString *domain = (error && error.domain) ? error.domain : @""; 229 BOOL isNetworkError = ([domain isEqualToString:(NSString *)kCFErrorDomainCFNetwork] || [domain isEqualToString:NSURLErrorDomain] || [domain isEqualToString:EXNetworkErrorDomain]); 230 231 if (isNetworkError) { 232 // show a human-readable reachability error 233 dispatch_async(dispatch_get_main_queue(), ^{ 234 [self _showErrorWithType:kEXFatalErrorTypeLoading error:error]; 235 }); 236 } else if ([domain isEqualToString:@"JSServer"] && [_appRecord.appManager enablesDeveloperTools]) { 237 // RCTRedBox already handled this 238 } else if ([domain rangeOfString:RCTErrorDomain].length > 0 && [_appRecord.appManager enablesDeveloperTools]) { 239 // RCTRedBox already handled this 240 } else { 241 dispatch_async(dispatch_get_main_queue(), ^{ 242 [self _showErrorWithType:kEXFatalErrorTypeException error:error]; 243 }); 244 } 245} 246 247- (void)refresh 248{ 249 self.isLoading = YES; 250 self.isBridgeAlreadyLoading = NO; 251 [self _invalidateRecoveryTimer]; 252 [_appRecord.appLoader request]; 253} 254 255- (void)reloadFromCache 256{ 257 self.isLoading = YES; 258 self.isBridgeAlreadyLoading = NO; 259 [self _invalidateRecoveryTimer]; 260 [_appRecord.appLoader requestFromCache]; 261} 262 263- (void)appStateDidBecomeActive 264{ 265 dispatch_async(dispatch_get_main_queue(), ^{ 266 // Reset the root view background color and window color if we switch between Expo home and project 267 [self _setBackgroundColor]; 268 }); 269} 270 271- (void)appStateDidBecomeInactive 272{ 273} 274 275- (void)_rebuildBridge 276{ 277 if (!self.isBridgeAlreadyLoading) { 278 self.isBridgeAlreadyLoading = YES; 279 dispatch_async(dispatch_get_main_queue(), ^{ 280 [self _overrideUserInterfaceStyleOf:self]; 281 [self _overrideAppearanceModuleBehaviour]; 282 [self _invalidateRecoveryTimer]; 283 [[EXKernel sharedInstance] logAnalyticsEvent:@"LOAD_EXPERIENCE" forAppRecord:self.appRecord]; 284 [self.appRecord.appManager rebuildBridge]; 285 }); 286 } 287} 288 289- (void)foregroundControllers 290{ 291 if (_backgroundedControllers != nil) { 292 __block UIViewController *parentController = self; 293 294 [_backgroundedControllers enumerateObjectsUsingBlock:^(UIViewController * _Nonnull viewController, NSUInteger idx, BOOL * _Nonnull stop) { 295 [parentController presentViewController:viewController animated:NO completion:nil]; 296 parentController = viewController; 297 }]; 298 299 _backgroundedControllers = nil; 300 } 301} 302 303- (void)backgroundControllers 304{ 305 UIViewController *childController = [self presentedViewController]; 306 307 if (childController != nil) { 308 if (_backgroundedControllers == nil) { 309 _backgroundedControllers = [NSMutableArray new]; 310 } 311 312 while (childController != nil) { 313 [_backgroundedControllers addObject:childController]; 314 childController = childController.presentedViewController; 315 } 316 } 317} 318 319/** 320 * In managed app we expect two kinds of manifest: 321 * - optimistic one (served from cache) 322 * - actual one served when app is fetched. 323 * For each of them we should show SplashScreen, 324 * therefore for any consecutive SplashScreen.show call we just reconfigure what's already visible. 325 * In HomeApp or standalone apps this function is no-op as SplashScreen is managed differently. 326 */ 327- (void)_showOrReconfigureManagedAppSplashScreen:(EXManifestsManifest *)manifest 328{ 329 if (_isStandalone || _isHomeApp) { 330 return; 331 } 332 if (!_managedAppSplashScreenViewProvider) { 333 _managedAppSplashScreenViewProvider = [[EXManagedAppSplashScreenViewProvider alloc] initWithManifest:manifest]; 334 335 [self _showManagedSplashScreenWithProvider:_managedAppSplashScreenViewProvider]; 336 } else { 337 [_managedAppSplashScreenViewProvider updateSplashScreenViewWithManifest:manifest]; 338 } 339} 340 341- (void)_showCachedExperienceAlert 342{ 343 if (self.isStandalone || self.isHomeApp) { 344 return; 345 } 346 347 dispatch_async(dispatch_get_main_queue(), ^{ 348 UIAlertController *alert = [UIAlertController 349 alertControllerWithTitle:@"Using a cached project" 350 message:@"If you did not intend to use a cached project, check your network connection and reload." 351 preferredStyle:UIAlertControllerStyleAlert]; 352 [alert addAction:[UIAlertAction actionWithTitle:@"Reload" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 353 [self refresh]; 354 }]]; 355 [alert addAction:[UIAlertAction actionWithTitle:@"Use cache" style:UIAlertActionStyleCancel handler:nil]]; 356 [self presentViewController:alert animated:YES completion:nil]; 357 }); 358} 359 360- (void)_setLoadingViewStatusIfEnabledFromAppLoader:(EXAppLoader *)appLoader 361{ 362 if (appLoader.shouldShowRemoteUpdateStatus) { 363 [self.appLoadingProgressWindowController updateStatus:appLoader.remoteUpdateStatus]; 364 } else { 365 [self.appLoadingProgressWindowController hide]; 366 } 367} 368 369- (void)_showSplashScreenWithProvider:(id<EXSplashScreenViewProvider>)provider 370{ 371 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 372 373 // EXSplashScreenService presents a splash screen on a root view controller 374 // at the start of the app. Since we want the EXAppViewController to manage 375 // the lifecycle of the splash screen we need to: 376 // 1. present the splash screen on EXAppViewController 377 // 2. hide the splash screen of root view controller 378 // Disclaimer: 379 // there's only one root view controller, but possibly many EXAppViewControllers 380 // (in Expo Go: one project -> one EXAppViewController) 381 // and we want to hide SplashScreen only once for the root view controller, hence the "once" 382 static dispatch_once_t once; 383 void (^hideRootViewControllerSplashScreen)(void) = ^void() { 384 dispatch_once(&once, ^{ 385 UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController; 386 [splashScreenService hideSplashScreenFor:rootViewController 387 options:EXSplashScreenDefault 388 successCallback:^(BOOL hasEffect){} 389 failureCallback:^(NSString * _Nonnull message) { 390 EXLogWarn(@"Hiding splash screen from root view controller did not succeed: %@", message); 391 }]; 392 }); 393 }; 394 395 EX_WEAKIFY(self); 396 dispatch_async(dispatch_get_main_queue(), ^{ 397 EX_ENSURE_STRONGIFY(self); 398 [splashScreenService showSplashScreenFor:self 399 options:EXSplashScreenDefault 400 splashScreenViewProvider:provider 401 successCallback:hideRootViewControllerSplashScreen 402 failureCallback:^(NSString *message){ EXLogWarn(@"%@", message); }]; 403 }); 404} 405 406- (void)_showManagedSplashScreenWithProvider:(id<EXSplashScreenViewProvider>)provider 407{ 408 409 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 410 411 EX_WEAKIFY(self); 412 dispatch_async(dispatch_get_main_queue(), ^{ 413 EX_ENSURE_STRONGIFY(self); 414 415 UIView *rootView = self.view; 416 UIView *splashScreenView = [provider createSplashScreenView]; 417 self.managedSplashScreenController = [[EXManagedAppSplashScreenViewController alloc] initWithRootView:rootView 418 splashScreenView:splashScreenView]; 419 [splashScreenService showSplashScreenFor:self 420 options:EXSplashScreenDefault 421 splashScreenController:self.managedSplashScreenController 422 successCallback:^{} 423 failureCallback:^(NSString *message){ EXLogWarn(@"%@", message); }]; 424 }); 425 426} 427 428- (void)hideLoadingProgressWindow 429{ 430 [self.appLoadingProgressWindowController hide]; 431 if (self.managedSplashScreenController) { 432 [self.managedSplashScreenController startSplashScreenVisibleTimer]; 433 } 434} 435 436#pragma mark - EXAppLoaderDelegate 437 438- (void)appLoader:(EXAppLoader *)appLoader didLoadOptimisticManifest:(EXManifestsManifest *)manifest 439{ 440 if (_appLoadingCancelView) { 441 EX_WEAKIFY(self); 442 dispatch_async(dispatch_get_main_queue(), ^{ 443 EX_ENSURE_STRONGIFY(self); 444 [self.appLoadingCancelView removeFromSuperview]; 445 self.appLoadingCancelView = nil; 446 }); 447 } 448 [self _showOrReconfigureManagedAppSplashScreen:manifest]; 449 [self _setLoadingViewStatusIfEnabledFromAppLoader:appLoader]; 450 if ([EXKernel sharedInstance].browserController) { 451 [[EXKernel sharedInstance].browserController addHistoryItemWithUrl:appLoader.manifestUrl manifest:manifest]; 452 } 453 [self _rebuildBridge]; 454} 455 456- (void)appLoader:(EXAppLoader *)appLoader didLoadBundleWithProgress:(EXLoadingProgress *)progress 457{ 458 if (self->_appRecord.appManager.status != kEXReactAppManagerStatusRunning) { 459 [self.appLoadingProgressWindowController updateStatusWithProgress:progress]; 460 } 461} 462 463- (void)appLoader:(EXAppLoader *)appLoader didFinishLoadingManifest:(EXManifestsManifest *)manifest bundle:(NSData *)data 464{ 465 [self _showOrReconfigureManagedAppSplashScreen:manifest]; 466 [self _rebuildBridge]; 467 if (self->_appRecord.appManager.status == kEXReactAppManagerStatusBridgeLoading) { 468 [self->_appRecord.appManager appLoaderFinished]; 469 } 470 471 if (!appLoader.isUpToDate && appLoader.shouldShowRemoteUpdateStatus) { 472 [self _showCachedExperienceAlert]; 473 } 474} 475 476- (void)appLoader:(EXAppLoader *)appLoader didFailWithError:(NSError *)error 477{ 478 if (_appRecord.appManager.status == kEXReactAppManagerStatusBridgeLoading) { 479 [_appRecord.appManager appLoaderFailedWithError:error]; 480 } 481 [self maybeShowError:error]; 482} 483 484- (void)appLoader:(EXAppLoader *)appLoader didResolveUpdatedBundleWithManifest:(EXManifestsManifest * _Nullable)manifest isFromCache:(BOOL)isFromCache error:(NSError * _Nullable)error 485{ 486 [[EXKernel sharedInstance].serviceRegistry.updatesManager notifyApp:_appRecord ofDownloadWithManifest:manifest isNew:!isFromCache error:error]; 487} 488 489#pragma mark - EXReactAppManagerDelegate 490 491- (void)reactAppManagerIsReadyForLoad:(EXReactAppManager *)appManager 492{ 493 UIView *reactView = appManager.rootView; 494 reactView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 495 reactView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 496 // Set this view to transparent so the root view background color aligns with custom development clients where the 497 // background color is the view controller root view. 498 reactView.backgroundColor = [UIColor clearColor]; 499 500 [_contentView removeFromSuperview]; 501 _contentView = reactView; 502 [self.view addSubview:_contentView]; 503 [self.view sendSubviewToBack:_contentView]; 504 [reactView becomeFirstResponder]; 505 506 // Set root view background color after adding as subview so we can access window 507 [self _setBackgroundColor]; 508} 509 510- (void)reactAppManagerStartedLoadingJavaScript:(EXReactAppManager *)appManager 511{ 512 EXAssertMainThread(); 513 self.isLoading = YES; 514} 515 516- (void)reactAppManagerFinishedLoadingJavaScript:(EXReactAppManager *)appManager 517{ 518 EXAssertMainThread(); 519 self.isLoading = NO; 520 if ([EXKernel sharedInstance].browserController) { 521 [[EXKernel sharedInstance].browserController appDidFinishLoadingSuccessfully:_appRecord]; 522 } 523} 524 525- (void)reactAppManagerAppContentDidAppear:(EXReactAppManager *)appManager 526{ 527 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 528 [splashScreenService onAppContentDidAppear:self]; 529} 530 531- (void)reactAppManagerAppContentWillReload:(EXReactAppManager *)appManager { 532 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 533 [splashScreenService onAppContentWillReload:self]; 534} 535 536- (void)reactAppManager:(EXReactAppManager *)appManager failedToLoadJavaScriptWithError:(NSError *)error 537{ 538 EXAssertMainThread(); 539 [self maybeShowError:error]; 540} 541 542- (void)reactAppManagerDidInvalidate:(EXReactAppManager *)appManager 543{ 544} 545 546- (void)errorViewDidSelectRetry:(EXErrorView *)errorView 547{ 548 [self refresh]; 549} 550 551#pragma mark - orientation 552 553- (UIInterfaceOrientationMask)supportedInterfaceOrientations 554{ 555 if ([self shouldUseRNScreenOrientation]) { 556 return [super supportedInterfaceOrientations]; 557 } 558 559#if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 560 EXScreenOrientationRegistry *screenOrientationRegistry = (EXScreenOrientationRegistry *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXScreenOrientationRegistry class]]; 561 if (screenOrientationRegistry && [screenOrientationRegistry requiredOrientationMask] > 0) { 562 return [screenOrientationRegistry requiredOrientationMask]; 563 } 564#endif 565 566 return [self orientationMaskFromManifestOrDefault]; 567} 568 569- (BOOL)shouldUseRNScreenOrientation 570{ 571 Class screenWindowTraitsClass = [self->_appRecord.appManager versionedClassFromString:@"RNSScreenWindowTraits"]; 572 if ([screenWindowTraitsClass respondsToSelector:@selector(shouldAskScreensForScreenOrientationInViewController:)]) { 573 id<EXKernelRNSScreenWindowTraits> screenWindowTraits = (id<EXKernelRNSScreenWindowTraits>)screenWindowTraitsClass; 574 return [screenWindowTraits shouldAskScreensForScreenOrientationInViewController:self]; 575 } 576 return NO; 577} 578 579- (UIInterfaceOrientationMask)orientationMaskFromManifestOrDefault { 580 if (_appRecord.appLoader.manifest) { 581 NSString *orientationConfig = _appRecord.appLoader.manifest.orientation; 582 if ([orientationConfig isEqualToString:@"portrait"]) { 583 // lock to portrait 584 return UIInterfaceOrientationMaskPortrait; 585 } else if ([orientationConfig isEqualToString:@"landscape"]) { 586 // lock to landscape 587 return UIInterfaceOrientationMaskLandscape; 588 } 589 } 590 // no config or default value: allow autorotation 591 return UIInterfaceOrientationMaskAllButUpsideDown; 592} 593 594- (void)traitCollectionDidChange:(nullable UITraitCollection *)previousTraitCollection { 595 [super traitCollectionDidChange:previousTraitCollection]; 596 if ((self.traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass) 597 || (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass)) { 598 599 #if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 600 EXScreenOrientationRegistry *screenOrientationRegistryController = (EXScreenOrientationRegistry *)[EXModuleRegistryProvider getSingletonModuleForClass:[EXScreenOrientationRegistry class]]; 601 [screenOrientationRegistryController traitCollectionDidChangeTo:self.traitCollection]; 602 #endif 603 } 604} 605 606#pragma mark - RCTAppearanceModule 607 608/** 609 * This function overrides behaviour of RCTAppearanceModule 610 * basing on 'userInterfaceStyle' option from the app manifest. 611 * It also defaults the RCTAppearanceModule to 'light'. 612 */ 613- (void)_overrideAppearanceModuleBehaviour 614{ 615 NSString *userInterfaceStyle = [self _readUserInterfaceStyleFromManifest:_appRecord.appLoader.manifest]; 616 NSString *appearancePreference = nil; 617 if ([userInterfaceStyle isEqualToString:@"light"]) { 618 appearancePreference = @"light"; 619 } else if ([userInterfaceStyle isEqualToString:@"dark"]) { 620 appearancePreference = @"dark"; 621 } else if ([userInterfaceStyle isEqualToString:@"automatic"]) { 622 appearancePreference = nil; 623 } 624 RCTOverrideAppearancePreference(appearancePreference); 625#if defined(INCLUDES_VERSIONED_CODE) && __has_include(<ABI46_0_0React/ABI46_0_0RCTAppearance.h>) 626 ABI46_0_0RCTOverrideAppearancePreference(appearancePreference); 627#endif 628#if defined(INCLUDES_VERSIONED_CODE) && __has_include(<ABI45_0_0React/ABI45_0_0RCTAppearance.h>) 629 ABI45_0_0RCTOverrideAppearancePreference(appearancePreference); 630#endif 631 632} 633 634#pragma mark - user interface style 635 636- (void)_overrideUserInterfaceStyleOf:(UIViewController *)viewController 637{ 638 if (@available(iOS 13.0, *)) { 639 NSString *userInterfaceStyle = [self _readUserInterfaceStyleFromManifest:_appRecord.appLoader.manifest]; 640 viewController.overrideUserInterfaceStyle = [self _userInterfaceStyleForString:userInterfaceStyle]; 641 } 642} 643 644- (NSString * _Nullable)_readUserInterfaceStyleFromManifest:(EXManifestsManifest *)manifest 645{ 646 return manifest.userInterfaceStyle; 647} 648 649- (UIUserInterfaceStyle)_userInterfaceStyleForString:(NSString *)userInterfaceStyleString API_AVAILABLE(ios(12.0)) { 650 if ([userInterfaceStyleString isEqualToString:@"dark"]) { 651 return UIUserInterfaceStyleDark; 652 } 653 if ([userInterfaceStyleString isEqualToString:@"automatic"]) { 654 return UIUserInterfaceStyleUnspecified; 655 } 656 if ([userInterfaceStyleString isEqualToString:@"light"]) { 657 return UIUserInterfaceStyleLight; 658 } 659 660 return UIUserInterfaceStyleUnspecified; 661} 662 663#pragma mark - root view and window background color 664 665- (void)_setBackgroundColor 666{ 667 NSString *backgroundColorString = [self _readBackgroundColorFromManifest:_appRecord.appLoader.manifest]; 668 UIColor *backgroundColor = [EXUtil colorWithHexString:backgroundColorString]; 669 self.view.backgroundColor = [UIColor clearColor]; 670 671 // NOTE(evanbacon): `self.view.window.rootViewController.view` represents the top-most window's root view controller's view which is the same 672 // view we set in `expo-system-ui`'s `setBackgroundColorAsync` method. 673 if (backgroundColor) { 674 if (self.view.window.rootViewController != nil && self.view.window.rootViewController.view != nil) { 675 self.view.window.rootViewController.view.backgroundColor = backgroundColor; 676 } 677 self.view.window.backgroundColor = backgroundColor; 678 } else { 679 // Reset this color to white so splash and other screens don't load against a black background. 680 if (self.view.window.rootViewController != nil && self.view.window.rootViewController.view != nil) { 681 self.view.window.rootViewController.view.backgroundColor = [UIColor whiteColor]; 682 } 683 // NOTE(brentvatne): we used to use white as a default background color for window but this caused 684 // problems when using form sheet presentation style with vcs eg: <Modal /> and native-stack. Most 685 // users expect the background behind these to be black, which is the default if backgroundColor is nil. 686 self.view.window.backgroundColor = nil; 687 688 // NOTE(brentvatne): we may want to default to respecting the default system background color 689 // on iOS13 and higher, but if we do make this choice then we will have to implement it on Android 690 // as well. This would also be a breaking change. Leaving this here as a placeholder for the future. 691 // if (@available(iOS 13.0, *)) { 692 // self.view.backgroundColor = [UIColor systemBackgroundColor]; 693 // } else { 694 // self.view.backgroundColor = [UIColor whiteColor]; 695 // } 696 } 697} 698 699- (NSString * _Nullable)_readBackgroundColorFromManifest:(EXManifestsManifest *)manifest 700{ 701 return manifest.iosOrRootBackgroundColor; 702} 703 704 705#pragma mark - Internal 706 707- (void)_showErrorWithType:(EXFatalErrorType)type error:(nullable NSError *)error 708{ 709 EXAssertMainThread(); 710 _dtmLastFatalErrorShown = [NSDate date]; 711 if (_errorView && _contentView == _errorView) { 712 // already showing, just update 713 _errorView.type = type; 714 _errorView.error = error; 715 } { 716 [_contentView removeFromSuperview]; 717 if (!_errorView) { 718 _errorView = [[EXErrorView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 719 _errorView.delegate = self; 720 _errorView.appRecord = _appRecord; 721 } 722 _errorView.type = type; 723 _errorView.error = error; 724 _contentView = _errorView; 725 [self.view addSubview:_contentView]; 726 [[EXAnalytics sharedInstance] logErrorVisibleEvent]; 727 } 728} 729 730- (void)setIsLoading:(BOOL)isLoading 731{ 732 if ([_appRecord.appManager enablesDeveloperTools] && _dtmLastFatalErrorShown) { 733 if ([_dtmLastFatalErrorShown timeIntervalSinceNow] >= -kEXDevelopmentErrorCoolDownSeconds) { 734 // we just showed a fatal error very recently, do not begin loading. 735 // this can happen in some cases where react native sends the 'started loading' notif 736 // in spite of a packager error. 737 return; 738 } 739 } 740 _isLoading = isLoading; 741 EX_WEAKIFY(self); 742 dispatch_async(dispatch_get_main_queue(), ^{ 743 EX_ENSURE_STRONGIFY(self); 744 if (!isLoading) { 745 [self.appLoadingProgressWindowController hide]; 746 } 747 }); 748} 749 750#pragma mark - error recovery 751 752- (BOOL)_willAutoRecoverFromError:(NSError *)error 753{ 754 if (![_appRecord.appManager enablesDeveloperTools]) { 755 BOOL shouldRecover = [[EXKernel sharedInstance].serviceRegistry.errorRecoveryManager experienceShouldReloadOnError:_appRecord.scopeKey]; 756 if (shouldRecover) { 757 [self _invalidateRecoveryTimer]; 758 _tmrAutoReloadDebounce = [NSTimer scheduledTimerWithTimeInterval:kEXAutoReloadDebounceSeconds 759 target:self 760 selector:@selector(refresh) 761 userInfo:nil 762 repeats:NO]; 763 } 764 return shouldRecover; 765 } 766 return NO; 767} 768 769- (void)_invalidateRecoveryTimer 770{ 771 if (_tmrAutoReloadDebounce) { 772 [_tmrAutoReloadDebounce invalidate]; 773 _tmrAutoReloadDebounce = nil; 774 } 775} 776 777#pragma mark - EXAppLoadingCancelViewDelegate 778 779- (void)appLoadingCancelViewDidCancel:(EXAppLoadingCancelView *)view { 780 if ([EXKernel sharedInstance].browserController) { 781 [[EXKernel sharedInstance].browserController moveHomeToVisible]; 782 } 783} 784 785@end 786 787NS_ASSUME_NONNULL_END 788