UnityAppController.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. #import "UnityAppController.h"
  2. #import "UnityAppController+ViewHandling.h"
  3. #import "UnityAppController+Rendering.h"
  4. #import "iPhone_Sensors.h"
  5. #import <CoreGraphics/CoreGraphics.h>
  6. #import <QuartzCore/QuartzCore.h>
  7. #import <QuartzCore/CADisplayLink.h>
  8. #import <Availability.h>
  9. #import <AVFoundation/AVFoundation.h>
  10. #include <mach/mach_time.h>
  11. // MSAA_DEFAULT_SAMPLE_COUNT was removed
  12. // ENABLE_INTERNAL_PROFILER and related defines were moved to iPhone_Profiler.h
  13. // kFPS define for removed: you can use Application.targetFrameRate (30 fps by default)
  14. // DisplayLink is the only run loop mode now - all others were removed
  15. #include "CrashReporter.h"
  16. #include "UI/OrientationSupport.h"
  17. #include "UI/UnityView.h"
  18. #include "UI/Keyboard.h"
  19. #include "UI/UnityViewControllerBase.h"
  20. #include "Unity/InternalProfiler.h"
  21. #include "Unity/DisplayManager.h"
  22. #include "Unity/ObjCRuntime.h"
  23. #include "PluginBase/AppDelegateListener.h"
  24. #include <assert.h>
  25. #include <stdbool.h>
  26. #include <sys/types.h>
  27. #include <unistd.h>
  28. #include <sys/sysctl.h>
  29. // we assume that app delegate is never changed and we can cache it, instead of re-query UIApplication every time
  30. UnityAppController* _UnityAppController = nil;
  31. UnityAppController* GetAppController()
  32. {
  33. return _UnityAppController;
  34. }
  35. // we keep old bools around to support "old" code that might have used them
  36. bool _ios81orNewer = false, _ios82orNewer = false, _ios83orNewer = false, _ios90orNewer = false, _ios91orNewer = false;
  37. bool _ios100orNewer = false, _ios101orNewer = false, _ios102orNewer = false, _ios103orNewer = false;
  38. bool _ios110orNewer = false, _ios111orNewer = false, _ios112orNewer = false;
  39. bool _ios130orNewer = false, _ios140orNewer = false, _ios150orNewer = false, _ios160orNewer = false;
  40. // minimal Unity initialization done, enough to do calls to provide data like URL launch
  41. bool _unityEngineLoaded = false;
  42. // was core of Unity loaded (non-graphics part prior to loading first scene)
  43. bool _unityEngineInitialized = false;
  44. // was unity rendering already inited: we should not touch rendering while this is false
  45. bool _renderingInited = false;
  46. // was unity inited: we should not touch unity api while this is false
  47. bool _unityAppReady = false;
  48. // see if there's a need to do internal player pause/resume handling
  49. //
  50. // Typically the trampoline code should manage this internally, but
  51. // there are use cases, videoplayer, plugin code, etc where the player
  52. // is paused before the internal handling comes relevant. Avoid
  53. // overriding externally managed player pause/resume handling by
  54. // caching the state
  55. bool _wasPausedExternal = false;
  56. // should we skip present on next draw: used in corner cases (like rotation) to fill both draw-buffers with some content
  57. bool _skipPresent = false;
  58. // was app "resigned active": some operations do not make sense while app is in background
  59. bool _didResignActive = false;
  60. #if UNITY_SUPPORT_ROTATION
  61. // Required to enable specific orientation for some presentation controllers: see supportedInterfaceOrientationsForWindow below for details
  62. NSInteger _forceInterfaceOrientationMask = 0;
  63. #endif
  64. @implementation UnityAppController
  65. @synthesize unityView = _unityView;
  66. @synthesize unityDisplayLink = _displayLink;
  67. @synthesize rootView = _rootView;
  68. @synthesize rootViewController = _rootController;
  69. @synthesize mainDisplay = _mainDisplay;
  70. @synthesize renderDelegate = _renderDelegate;
  71. @synthesize quitHandler = _quitHandler;
  72. #if UNITY_SUPPORT_ROTATION
  73. @synthesize interfaceOrientation = _curOrientation;
  74. #endif
  75. - (id)init
  76. {
  77. if ((self = _UnityAppController = [super init]))
  78. {
  79. // due to clang issues with generating warning for overriding deprecated methods
  80. // we will simply assert if deprecated methods are present
  81. // NB: methods table is initied at load (before this call), so it is ok to check for override
  82. NSAssert(![self respondsToSelector: @selector(createUnityViewImpl)],
  83. @"createUnityViewImpl is deprecated and will not be called. Override createUnityView"
  84. );
  85. NSAssert(![self respondsToSelector: @selector(createViewHierarchyImpl)],
  86. @"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"
  87. );
  88. NSAssert(![self respondsToSelector: @selector(createViewHierarchy)],
  89. @"createViewHierarchy is deprecated and will not be implemented. Use createUI"
  90. );
  91. }
  92. return self;
  93. }
  94. - (void)setWindow:(id)object {}
  95. - (UIWindow*)window { return _window; }
  96. - (void)shouldAttachRenderDelegate {}
  97. - (void)preStartUnity {}
  98. - (void)startUnity:(UIApplication*)application
  99. {
  100. NSAssert(_unityAppReady == NO, @"[UnityAppController startUnity:] called after Unity has been initialized");
  101. UnityInitApplicationGraphics();
  102. #if !PLATFORM_VISIONOS
  103. // we make sure that first level gets correct display list and orientation
  104. [[DisplayManager Instance] updateDisplayListCacheInUnity];
  105. #endif
  106. UnityLoadApplication();
  107. Profiler_InitProfiler();
  108. [self showGameUI];
  109. [self createDisplayLink];
  110. UnitySetPlayerFocus(1);
  111. AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  112. // If Unity audio is disabled, we set the category to ambient to make sure we don't mute other app's audio. We set the audio session
  113. // to active so we can get outputVolume callbacks. If Unity audio is enabled, FMOD should have already handled all of this AVAudioSession init.
  114. if (!UnityIsAudioManagerAvailableAndEnabled())
  115. {
  116. [audioSession setCategory: AVAudioSessionCategoryAmbient error: nil];
  117. [audioSession setActive: YES error: nil];
  118. }
  119. [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
  120. UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
  121. #if UNITY_REPLAY_KIT_AVAILABLE
  122. void InitUnityReplayKit(); // Classes/Unity/UnityReplayKit.mm
  123. InitUnityReplayKit();
  124. #endif
  125. }
  126. extern "C" void UnityDestroyDisplayLink()
  127. {
  128. [GetAppController() destroyDisplayLink];
  129. }
  130. extern "C" void UnityRequestUnload()
  131. {
  132. _unityAppReady = false;
  133. [[NSNotificationCenter defaultCenter] postNotificationName: kUnityDidUnload object: nil];
  134. }
  135. extern "C" void UnityRequestQuit()
  136. {
  137. _didResignActive = true;
  138. if (GetAppController().quitHandler)
  139. GetAppController().quitHandler();
  140. else
  141. exit(0);
  142. }
  143. extern void SensorsCleanup();
  144. extern "C" void UnityCleanupTrampoline()
  145. {
  146. // Prevent multiple cleanups
  147. if (_UnityAppController == nil)
  148. return;
  149. // Unity view and viewController will not necessary be destroyed right after this function execution.
  150. // We need to ensure that these objects will not receive any callbacks from system during that time.
  151. _UnityAppController.window.rootViewController = nil;
  152. [_UnityAppController.unityView removeFromSuperview];
  153. [KeyboardDelegate Destroy];
  154. SensorsCleanup();
  155. Profiler_UninitProfiler();
  156. [DisplayManager Destroy];
  157. UnityDestroyDisplayLink();
  158. _UnityAppController = nil;
  159. }
  160. #if UNITY_SUPPORT_ROTATION
  161. - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
  162. {
  163. // No rootViewController is set because we are switching from one view controller to another, all orientations should be enabled
  164. if ([window rootViewController] == nil)
  165. return UIInterfaceOrientationMaskAll;
  166. // During splash screen show phase no forced orientations should be allowed.
  167. // This will prevent unwanted rotation while splash screen is on and application is not yet ready to present (Ex. Fogbugz cases: 1190428, 1269547).
  168. if (!_unityAppReady)
  169. return [_rootController supportedInterfaceOrientations];
  170. // Some presentation controllers (e.g. UIImagePickerController) require portrait orientation and will throw exception if it is not supported.
  171. // At the same time enabling all orientations by returning UIInterfaceOrientationMaskAll might cause unwanted orientation change
  172. // (e.g. when using UIActivityViewController to "share to" another application, iOS will use supportedInterfaceOrientations to possibly reorient).
  173. // So to avoid exception we are returning combination of constraints for root view controller and orientation requested by iOS.
  174. // _forceInterfaceOrientationMask is updated in willChangeStatusBarOrientation, which is called if some presentation controller insists on orientation change.
  175. return [[window rootViewController] supportedInterfaceOrientations] | _forceInterfaceOrientationMask;
  176. }
  177. - (void)application:(UIApplication*)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
  178. {
  179. // Setting orientation mask which is requested by iOS: see supportedInterfaceOrientationsForWindow above for details
  180. _forceInterfaceOrientationMask = 1 << newStatusBarOrientation;
  181. }
  182. #endif
  183. #if UNITY_USES_REMOTE_NOTIFICATIONS
  184. - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
  185. {
  186. AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
  187. }
  188. #if !PLATFORM_TVOS
  189. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
  190. {
  191. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  192. if (handler)
  193. {
  194. handler(UIBackgroundFetchResultNoData);
  195. }
  196. }
  197. #endif
  198. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
  199. {
  200. AppController_SendNotificationWithArg(kUnityDidFailToRegisterForRemoteNotificationsWithError, error);
  201. // alas people do not check remote notification error through api (which is clunky, i agree) so log here to have at least some visibility
  202. ::printf("\nFailed to register for remote notifications:\n%s\n\n", [[error localizedDescription] UTF8String]);
  203. }
  204. #endif
  205. // UIApplicationOpenURLOptionsKey was added only in ios10 sdk, while we still support ios9 sdk
  206. - (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString*, id>*)options
  207. {
  208. id sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey], annotation = options[UIApplicationOpenURLOptionsAnnotationKey];
  209. NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
  210. if (url)
  211. {
  212. notifData[@"url"] = url;
  213. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  214. }
  215. if (sourceApplication) notifData[@"sourceApplication"] = sourceApplication;
  216. if (annotation) notifData[@"annotation"] = annotation;
  217. AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
  218. return YES;
  219. }
  220. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > * _Nullable restorableObjects))restorationHandler
  221. {
  222. NSURL* url = userActivity.webpageURL;
  223. if (url)
  224. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  225. return YES;
  226. }
  227. - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  228. {
  229. AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
  230. NSURL* url = [self extractURLFromLaunchOptions: launchOptions];
  231. if (url != nil)
  232. {
  233. [self initUnityApplicationNoGraphics];
  234. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  235. }
  236. return YES;
  237. }
  238. // Helper method to extract URL from launch options
  239. - (NSURL*)extractURLFromLaunchOptions:(NSDictionary*)launchOptions
  240. {
  241. // Check for the direct launch URL
  242. NSURL* url = launchOptions[UIApplicationLaunchOptionsURLKey];
  243. if (url != nil)
  244. {
  245. return url;
  246. }
  247. // Check for the user activity dictionary and URL from user activity
  248. NSUserActivity* userActivity = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey][@"UIApplicationLaunchOptionsUserActivityKey"];
  249. if (userActivity != nil && [userActivity.activityType isEqualToString: NSUserActivityTypeBrowsingWeb])
  250. {
  251. url = userActivity.webpageURL;
  252. if (url != nil)
  253. {
  254. return url;
  255. }
  256. }
  257. return nil;
  258. }
  259. - (UIWindowScene*)pickStartupWindowScene:(NSSet<UIScene*>*)scenes API_AVAILABLE(ios(13.0), tvos(13.0))
  260. {
  261. // if we have scene with UISceneActivationStateForegroundActive - pick it
  262. // otherwise UISceneActivationStateForegroundInactive will work
  263. // it will be the scene going into active state
  264. // if there were no active/inactive scenes (only background) we should allow background scene
  265. // this might happen in some cases with native plugins doing "things"
  266. UIWindowScene *foregroundScene = nil, *backgroundScene = nil;
  267. for (UIScene* scene in scenes)
  268. {
  269. if (![scene isKindOfClass: [UIWindowScene class]])
  270. continue;
  271. UIWindowScene* windowScene = (UIWindowScene*)scene;
  272. if (scene.activationState == UISceneActivationStateForegroundActive)
  273. return windowScene;
  274. if (scene.activationState == UISceneActivationStateForegroundInactive)
  275. foregroundScene = windowScene;
  276. else if (scene.activationState == UISceneActivationStateBackground)
  277. backgroundScene = windowScene;
  278. }
  279. return foregroundScene ? foregroundScene : backgroundScene;
  280. }
  281. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  282. {
  283. ::printf("-> applicationDidFinishLaunching()\n");
  284. // send notfications
  285. #if !PLATFORM_TVOS && !PLATFORM_VISIONOS
  286. if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
  287. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  288. #endif
  289. // if application is in background, don't initialize Unity
  290. // this happens if app uses location fence, notifications with content/actions, ...
  291. // initUnityWithApplication: initializes rendering, possibly loads scene and calls Start(), none meant for background
  292. if (UIApplication.sharedApplication.applicationState == UIApplicationStateBackground)
  293. return YES;
  294. [self initUnityWithApplication: application];
  295. return YES;
  296. }
  297. - (void)initUnityApplicationNoGraphics
  298. {
  299. if (_unityEngineLoaded)
  300. return;
  301. _unityEngineLoaded = true;
  302. UnityInitApplicationNoGraphics(UnityDataBundleDir());
  303. }
  304. - (void)initUnityWithApplication:(UIApplication*)application
  305. {
  306. if (_unityEngineInitialized)
  307. return;
  308. _unityEngineInitialized = true;
  309. // basic unity init
  310. [self initUnityApplicationNoGraphics];
  311. [self selectRenderingAPI];
  312. [UnityRenderingView InitializeForAPI: self.renderingAPI];
  313. #if !PLATFORM_VISIONOS
  314. if (@available(iOS 13, tvOS 13, *))
  315. _window = [[UIWindow alloc] initWithWindowScene: [self pickStartupWindowScene: application.connectedScenes]];
  316. else
  317. _window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
  318. #else
  319. _window = [[UIWindow alloc] init];
  320. #endif
  321. _unityView = [self createUnityView];
  322. [DisplayManager Initialize];
  323. _mainDisplay = [DisplayManager Instance].mainDisplay;
  324. [_mainDisplay createWithWindow: _window andView: _unityView];
  325. [self createUI];
  326. [self preStartUnity];
  327. // if you wont use keyboard you may comment it out at save some memory
  328. [KeyboardDelegate Initialize];
  329. #if UNITY_DEVELOPER_BUILD
  330. // Causes a black screen after splash screen, but would deadlock if waiting for manged debugger otherwise
  331. [self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
  332. #else
  333. [self startUnity: application];
  334. #endif
  335. }
  336. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
  337. {
  338. if ([keyPath isEqual: @"outputVolume"])
  339. {
  340. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  341. }
  342. }
  343. - (void)applicationDidEnterBackground:(UIApplication*)application
  344. {
  345. ::printf("-> applicationDidEnterBackground()\n");
  346. }
  347. - (void)applicationWillEnterForeground:(UIApplication*)application
  348. {
  349. ::printf("-> applicationWillEnterForeground()\n");
  350. // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
  351. if (_unityAppReady)
  352. {
  353. // if we were showing video before going to background - the view size may be changed while we are in background
  354. [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
  355. }
  356. }
  357. - (void)applicationDidBecomeActive:(UIApplication*)application
  358. {
  359. ::printf("-> applicationDidBecomeActive()\n");
  360. [self removeSnapshotViewController];
  361. if (_unityAppReady)
  362. {
  363. if (UnityIsPaused() && _wasPausedExternal == false)
  364. {
  365. UnityWillResume();
  366. UnityPause(0);
  367. }
  368. if (_wasPausedExternal)
  369. {
  370. if (UnityIsFullScreenPlaying())
  371. TryResumeFullScreenVideo();
  372. }
  373. // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
  374. [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
  375. UnitySetPlayerFocus(1);
  376. }
  377. else
  378. {
  379. [self initUnityWithApplication: application];
  380. }
  381. _didResignActive = false;
  382. }
  383. - (void)updateUnityAudioOutput
  384. {
  385. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  386. }
  387. - (void)addSnapshotViewController
  388. {
  389. if (!_didResignActive || self->_snapshotViewController)
  390. {
  391. return;
  392. }
  393. UIView* snapshotView = [self createSnapshotView];
  394. if (snapshotView != nil)
  395. {
  396. UIViewController* snapshotViewController = [AllocUnityViewController() init];
  397. snapshotViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  398. snapshotViewController.view = snapshotView;
  399. [self->_rootController presentViewController: snapshotViewController animated: false completion: nil];
  400. self->_snapshotViewController = snapshotViewController;
  401. }
  402. }
  403. - (void)removeSnapshotViewController
  404. {
  405. // do this on the main queue async so that if we try to create one
  406. // and remove in the same frame, this always happens after in the same queue
  407. dispatch_async(dispatch_get_main_queue(), ^{
  408. if (self->_snapshotViewController)
  409. {
  410. // we've got a view on top of the snapshot view (3rd party plugin/social media login etc).
  411. if (self->_snapshotViewController.presentedViewController)
  412. {
  413. [self performSelector: @selector(removeSnapshotViewController) withObject: nil afterDelay: 0.05];
  414. return;
  415. }
  416. [self->_snapshotViewController dismissViewControllerAnimated: NO completion: nil];
  417. self->_snapshotViewController = nil;
  418. // Make sure that the keyboard input field regains focus after the application becomes active.
  419. [[KeyboardDelegate Instance] becomeFirstResponder];
  420. }
  421. });
  422. }
  423. - (void)applicationWillResignActive:(UIApplication*)application
  424. {
  425. ::printf("-> applicationWillResignActive()\n");
  426. if (_unityAppReady)
  427. {
  428. UnitySetPlayerFocus(0);
  429. // signal unity that the frame rendering have ended
  430. // as we will not get the callback from the display link current frame
  431. UnityDisplayLinkCallback(0);
  432. _wasPausedExternal = UnityIsPaused();
  433. if (_wasPausedExternal == false)
  434. {
  435. // Pause Unity only if we don't need special background processing
  436. // otherwise batched player loop can be called to run user scripts.
  437. if (!UnityGetUseCustomAppBackgroundBehavior())
  438. {
  439. #if UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE
  440. // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
  441. // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
  442. // NB: We will actually pause after the loop (when calling UnityPause).
  443. UnityWillPause();
  444. [self repaint];
  445. UnityWaitForFrame();
  446. [self addSnapshotViewController];
  447. #endif
  448. UnityPause(1);
  449. }
  450. }
  451. }
  452. _didResignActive = true;
  453. }
  454. - (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
  455. {
  456. UnityLowMemory();
  457. }
  458. - (void)applicationWillTerminate:(UIApplication*)application
  459. {
  460. ::printf("-> applicationWillTerminate()\n");
  461. // Only clean up if Unity has finished initializing, else the clean up process will crash,
  462. // this happens if the app is force closed immediately after opening it.
  463. if (_unityAppReady)
  464. {
  465. // make sure that we are in a "unity cannot be touched" state
  466. // if there was some complex UI shown when terminating, we can get extra UI calls from iOS after applicationWillTerminate:
  467. // and we want to make sure we never do anything touching unity runtime at this point
  468. _unityAppReady = _renderingInited = _unityEngineInitialized = false;
  469. _didResignActive = true;
  470. UnityCleanup();
  471. UnityCleanupTrampoline();
  472. }
  473. }
  474. - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
  475. {
  476. NSDictionary* arg = @{identifier: completionHandler};
  477. AppController_SendNotificationWithArg(kUnityHandleEventsForBackgroundURLSession, arg);
  478. }
  479. @end
  480. void AppController_SendNotification(NSString* name)
  481. {
  482. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController()];
  483. }
  484. void AppController_SendNotificationWithArg(NSString* name, id arg)
  485. {
  486. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
  487. }
  488. void AppController_SendUnityViewControllerNotification(NSString* name)
  489. {
  490. [[NSNotificationCenter defaultCenter] postNotificationName: name object: UnityGetGLViewController()];
  491. }
  492. extern "C" UIWindow* UnityGetMainWindow() { return GetAppController().mainDisplay.window; }
  493. extern "C" UIViewController* UnityGetGLViewController() { return GetAppController().rootViewController; }
  494. extern "C" UnityView* UnityGetUnityView() { return GetAppController().unityView; }
  495. extern "C" UIView* UnityGetGLView() { return UnityGetUnityView(); }
  496. extern "C" ScreenOrientation UnityCurrentOrientation() { return GetAppController().unityView.contentOrientation; }
  497. bool LogToNSLogHandler(LogType logType, const char* log, va_list list)
  498. {
  499. NSLogv([NSString stringWithUTF8String: log], list);
  500. return true;
  501. }
  502. static void AddNewAPIImplIfNeeded();
  503. // From https://stackoverflow.com/questions/4744826/detecting-if-ios-app-is-run-in-debugger
  504. static bool isDebuggerAttachedToConsole(void)
  505. // Returns true if the current process is being debugged (either
  506. // running under the debugger or has a debugger attached post facto).
  507. {
  508. int junk;
  509. int mib[4];
  510. struct kinfo_proc info;
  511. size_t size;
  512. // Initialize the flags so that, if sysctl fails for some bizarre
  513. // reason, we get a predictable result.
  514. info.kp_proc.p_flag = 0;
  515. // Initialize mib, which tells sysctl the info we want, in this case
  516. // we're looking for information about a specific process ID.
  517. mib[0] = CTL_KERN;
  518. mib[1] = KERN_PROC;
  519. mib[2] = KERN_PROC_PID;
  520. mib[3] = getpid();
  521. // Call sysctl.
  522. size = sizeof(info);
  523. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  524. assert(junk == 0);
  525. // We're being debugged if the P_TRACED flag is set.
  526. // But if we are starting app on device (and make debugger wait and attach after start)
  527. // it will NOT connect stout (only stderr, used by nslog)
  528. // Hence we also check that stoud is rerouted
  529. return ((info.kp_proc.p_flag & P_TRACED) != 0) && isatty(STDOUT_FILENO);
  530. }
  531. void UnityInitTrampoline()
  532. {
  533. InitCrashHandling();
  534. NSString* version = [[UIDevice currentDevice] systemVersion];
  535. #define CHECK_VER(s) [version compare: s options: NSNumericSearch] != NSOrderedAscending
  536. _ios81orNewer = CHECK_VER(@"8.1"); _ios82orNewer = CHECK_VER(@"8.2"); _ios83orNewer = CHECK_VER(@"8.3");
  537. _ios90orNewer = CHECK_VER(@"9.0"); _ios91orNewer = CHECK_VER(@"9.1");
  538. _ios100orNewer = CHECK_VER(@"10.0"); _ios101orNewer = CHECK_VER(@"10.1"); _ios102orNewer = CHECK_VER(@"10.2"); _ios103orNewer = CHECK_VER(@"10.3");
  539. _ios110orNewer = CHECK_VER(@"11.0"); _ios111orNewer = CHECK_VER(@"11.1"); _ios112orNewer = CHECK_VER(@"11.2");
  540. _ios130orNewer = CHECK_VER(@"13.0"); _ios140orNewer = CHECK_VER(@"14.0"); _ios150orNewer = CHECK_VER(@"15.0");
  541. _ios160orNewer = CHECK_VER(@"16.0");
  542. #undef CHECK_VER
  543. AddNewAPIImplIfNeeded();
  544. #if !TARGET_IPHONE_SIMULATOR
  545. // Use NSLog logging if a debugger is not attached, otherwise we write to stdout.
  546. if (!isDebuggerAttachedToConsole())
  547. UnitySetLogEntryHandler(LogToNSLogHandler);
  548. #endif
  549. }
  550. extern "C" bool UnityiOS81orNewer() { return _ios81orNewer; }
  551. extern "C" bool UnityiOS82orNewer() { return _ios82orNewer; }
  552. extern "C" bool UnityiOS90orNewer() { return _ios90orNewer; }
  553. extern "C" bool UnityiOS91orNewer() { return _ios91orNewer; }
  554. extern "C" bool UnityiOS100orNewer() { return _ios100orNewer; }
  555. extern "C" bool UnityiOS101orNewer() { return _ios101orNewer; }
  556. extern "C" bool UnityiOS102orNewer() { return _ios102orNewer; }
  557. extern "C" bool UnityiOS103orNewer() { return _ios103orNewer; }
  558. extern "C" bool UnityiOS110orNewer() { return _ios110orNewer; }
  559. extern "C" bool UnityiOS111orNewer() { return _ios111orNewer; }
  560. extern "C" bool UnityiOS112orNewer() { return _ios112orNewer; }
  561. extern "C" bool UnityiOS130orNewer() { return _ios130orNewer; }
  562. extern "C" bool UnityiOS140orNewer() { return _ios140orNewer; }
  563. extern "C" bool UnityiOS150orNewer() { return _ios150orNewer; }
  564. extern "C" bool UnityiOS160orNewer() { return _ios160orNewer; }
  565. // sometimes apple adds new api with obvious fallback on older ios.
  566. // in that case we simply add these functions ourselves to simplify code
  567. static void AddNewAPIImplIfNeeded()
  568. {
  569. #if !PLATFORM_VISIONOS
  570. if (![[UIScreen class] instancesRespondToSelector: @selector(maximumFramesPerSecond)])
  571. {
  572. IMP UIScreen_MaximumFramesPerSecond_IMP = imp_implementationWithBlock(^NSInteger(id _self) {
  573. return 60;
  574. });
  575. class_replaceMethod([UIScreen class], @selector(maximumFramesPerSecond), UIScreen_MaximumFramesPerSecond_IMP, UIScreen_maximumFramesPerSecond_Enc);
  576. }
  577. if (![[UIView class] instancesRespondToSelector: @selector(safeAreaInsets)])
  578. {
  579. IMP UIView_SafeAreaInsets_IMP = imp_implementationWithBlock(^UIEdgeInsets(id _self) {
  580. return UIEdgeInsetsZero;
  581. });
  582. class_replaceMethod([UIView class], @selector(safeAreaInsets), UIView_SafeAreaInsets_IMP, UIView_safeAreaInsets_Enc);
  583. }
  584. #endif
  585. }