UnityAppController.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. #import <OpenGLES/EAGL.h>
  11. #import <OpenGLES/EAGLDrawable.h>
  12. #import <OpenGLES/ES2/gl.h>
  13. #import <OpenGLES/ES2/glext.h>
  14. #include <mach/mach_time.h>
  15. // MSAA_DEFAULT_SAMPLE_COUNT was moved to iPhone_GlesSupport.h
  16. // ENABLE_INTERNAL_PROFILER and related defines were moved to iPhone_Profiler.h
  17. // kFPS define for removed: you can use Application.targetFrameRate (30 fps by default)
  18. // DisplayLink is the only run loop mode now - all others were removed
  19. #include "CrashReporter.h"
  20. #include "UI/OrientationSupport.h"
  21. #include "UI/UnityView.h"
  22. #include "UI/Keyboard.h"
  23. #include "UI/SplashScreen.h"
  24. #include "Unity/InternalProfiler.h"
  25. #include "Unity/DisplayManager.h"
  26. #include "Unity/EAGLContextHelper.h"
  27. #include "Unity/GlesHelper.h"
  28. #include "Unity/ObjCRuntime.h"
  29. #include "PluginBase/AppDelegateListener.h"
  30. #include <assert.h>
  31. #include <stdbool.h>
  32. #include <sys/types.h>
  33. #include <unistd.h>
  34. #include <sys/sysctl.h>
  35. #import "IOSPlatformSDK.h"
  36. // we assume that app delegate is never changed and we can cache it, instead of re-query UIApplication every time
  37. UnityAppController* _UnityAppController = nil;
  38. UnityAppController* GetAppController()
  39. {
  40. return _UnityAppController;
  41. }
  42. // we keep old bools around to support "old" code that might have used them
  43. bool _ios81orNewer = false, _ios82orNewer = false, _ios83orNewer = false, _ios90orNewer = false, _ios91orNewer = false;
  44. bool _ios100orNewer = false, _ios101orNewer = false, _ios102orNewer = false, _ios103orNewer = false;
  45. bool _ios110orNewer = false, _ios111orNewer = false, _ios112orNewer = false;
  46. bool _ios130orNewer = false;
  47. // was unity rendering already inited: we should not touch rendering while this is false
  48. bool _renderingInited = false;
  49. // was unity inited: we should not touch unity api while this is false
  50. bool _unityAppReady = false;
  51. // see if there's a need to do internal player pause/resume handling
  52. //
  53. // Typically the trampoline code should manage this internally, but
  54. // there are use cases, videoplayer, plugin code, etc where the player
  55. // is paused before the internal handling comes relevant. Avoid
  56. // overriding externally managed player pause/resume handling by
  57. // caching the state
  58. bool _wasPausedExternal = false;
  59. // should we skip present on next draw: used in corner cases (like rotation) to fill both draw-buffers with some content
  60. bool _skipPresent = false;
  61. // was app "resigned active": some operations do not make sense while app is in background
  62. bool _didResignActive = false;
  63. // was startUnity scheduled: used to make startup robust in case of locking device
  64. static bool _startUnityScheduled = false;
  65. bool _supportsMSAA = false;
  66. #if UNITY_SUPPORT_ROTATION
  67. // Required to enable specific orientation for some presentation controllers: see supportedInterfaceOrientationsForWindow below for details
  68. NSInteger _forceInterfaceOrientationMask = 0;
  69. #endif
  70. @implementation UnityAppController
  71. @synthesize unityView = _unityView;
  72. @synthesize unityDisplayLink = _displayLink;
  73. @synthesize rootView = _rootView;
  74. @synthesize rootViewController = _rootController;
  75. @synthesize mainDisplay = _mainDisplay;
  76. @synthesize renderDelegate = _renderDelegate;
  77. @synthesize quitHandler = _quitHandler;
  78. #if UNITY_SUPPORT_ROTATION
  79. @synthesize interfaceOrientation = _curOrientation;
  80. #endif
  81. - (id)init
  82. {
  83. if ((self = _UnityAppController = [super init]))
  84. {
  85. // due to clang issues with generating warning for overriding deprecated methods
  86. // we will simply assert if deprecated methods are present
  87. // NB: methods table is initied at load (before this call), so it is ok to check for override
  88. NSAssert(![self respondsToSelector: @selector(createUnityViewImpl)],
  89. @"createUnityViewImpl is deprecated and will not be called. Override createUnityView"
  90. );
  91. NSAssert(![self respondsToSelector: @selector(createViewHierarchyImpl)],
  92. @"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"
  93. );
  94. NSAssert(![self respondsToSelector: @selector(createViewHierarchy)],
  95. @"createViewHierarchy is deprecated and will not be implemented. Use createUI"
  96. );
  97. }
  98. return self;
  99. }
  100. - (void)setWindow:(id)object {}
  101. - (UIWindow*)window { return _window; }
  102. - (void)shouldAttachRenderDelegate {}
  103. - (void)preStartUnity {}
  104. - (void)startUnity:(UIApplication*)application
  105. {
  106. NSAssert(_unityAppReady == NO, @"[UnityAppController startUnity:] called after Unity has been initialized");
  107. UnityInitApplicationGraphics();
  108. // we make sure that first level gets correct display list and orientation
  109. [[DisplayManager Instance] updateDisplayListCacheInUnity];
  110. UnityLoadApplication();
  111. Profiler_InitProfiler();
  112. [self showGameUI];
  113. [self createDisplayLink];
  114. UnitySetPlayerFocus(1);
  115. AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  116. [audioSession setActive: YES error: nil];
  117. [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
  118. UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
  119. }
  120. extern "C" void UnityDestroyDisplayLink()
  121. {
  122. [GetAppController() destroyDisplayLink];
  123. }
  124. extern "C" void UnityRequestQuit()
  125. {
  126. _didResignActive = true;
  127. if (GetAppController().quitHandler)
  128. GetAppController().quitHandler();
  129. else
  130. exit(0);
  131. }
  132. extern void SensorsCleanup();
  133. extern "C" void UnityCleanupTrampoline()
  134. {
  135. // Unity view and viewController will not necessary be destroyed right after this function execution.
  136. // We need to ensure that these objects will not receive any callbacks from system during that time.
  137. [_UnityAppController window].rootViewController = nil;
  138. [[_UnityAppController unityView] removeFromSuperview];
  139. // Prevent multiple cleanups
  140. if (_UnityAppController == nil)
  141. return;
  142. [KeyboardDelegate Destroy];
  143. SensorsCleanup();
  144. Profiler_UninitProfiler();
  145. [DisplayManager Destroy];
  146. UnityDestroyDisplayLink();
  147. _UnityAppController = nil;
  148. }
  149. #if UNITY_SUPPORT_ROTATION
  150. - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
  151. {
  152. // No rootViewController is set because we are switching from one view controller to another, all orientations should be enabled
  153. if ([window rootViewController] == nil)
  154. return UIInterfaceOrientationMaskAll;
  155. // Some presentation controllers (e.g. UIImagePickerController) require portrait orientation and will throw exception if it is not supported.
  156. // At the same time enabling all orientations by returning UIInterfaceOrientationMaskAll might cause unwanted orientation change
  157. // (e.g. when using UIActivityViewController to "share to" another application, iOS will use supportedInterfaceOrientations to possibly reorient).
  158. // So to avoid exception we are returning combination of constraints for root view controller and orientation requested by iOS.
  159. // _forceInterfaceOrientationMask is updated in willChangeStatusBarOrientation, which is called if some presentation controller insists on orientation change.
  160. return [[window rootViewController] supportedInterfaceOrientations] | _forceInterfaceOrientationMask;
  161. }
  162. - (void)application:(UIApplication*)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
  163. {
  164. // Setting orientation mask which is requested by iOS: see supportedInterfaceOrientationsForWindow above for details
  165. _forceInterfaceOrientationMask = 1 << newStatusBarOrientation;
  166. }
  167. #endif
  168. #if !PLATFORM_TVOS
  169. - (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification*)notification
  170. {
  171. AppController_SendNotificationWithArg(kUnityDidReceiveLocalNotification, notification);
  172. UnitySendLocalNotification(notification);
  173. }
  174. #endif
  175. #if UNITY_USES_REMOTE_NOTIFICATIONS
  176. - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
  177. {
  178. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  179. UnitySendRemoteNotification(userInfo);
  180. }
  181. - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
  182. {
  183. AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
  184. UnitySendDeviceToken(deviceToken);
  185. }
  186. #if !PLATFORM_TVOS
  187. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
  188. {
  189. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  190. UnitySendRemoteNotification(userInfo);
  191. if (handler)
  192. {
  193. handler(UIBackgroundFetchResultNoData);
  194. }
  195. }
  196. #endif
  197. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
  198. {
  199. AppController_SendNotificationWithArg(kUnityDidFailToRegisterForRemoteNotificationsWithError, error);
  200. UnitySendRemoteNotificationError(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. [[IOSPlatformSDK sharedInstance] startWithUrl:url];
  219. return YES;
  220. }
  221. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
  222. #if defined(__IPHONE_12_0) || defined(__TVOS_12_0)
  223. restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > * _Nullable restorableObjects))restorationHandler
  224. #else
  225. restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
  226. #endif
  227. {
  228. NSURL* url = userActivity.webpageURL;
  229. if (url)
  230. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  231. return YES;
  232. }
  233. - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  234. {
  235. AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
  236. return YES;
  237. }
  238. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  239. {
  240. ::printf("-> applicationDidFinishLaunching()\n");
  241. // send notfications
  242. #if !PLATFORM_TVOS
  243. if (UILocalNotification* notification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey])
  244. UnitySendLocalNotification(notification);
  245. if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
  246. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  247. #endif
  248. UnityInitApplicationNoGraphics(UnityDataBundleDir());
  249. [self selectRenderingAPI];
  250. [UnityRenderingView InitializeForAPI: self.renderingAPI];
  251. _window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
  252. _unityView = [self createUnityView];
  253. [DisplayManager Initialize];
  254. _mainDisplay = [DisplayManager Instance].mainDisplay;
  255. [_mainDisplay createWithWindow: _window andView: _unityView];
  256. [self createUI];
  257. [self preStartUnity];
  258. // if you wont use keyboard you may comment it out at save some memory
  259. [KeyboardDelegate Initialize];
  260. // //以下是几种打开App方式
  261. // if(launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]){
  262. // NSLog(@"打开方式 远程推送打开");
  263. // }else if(launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]){
  264. // NSLog(@"打开方式 本地推送打开");
  265. // }else if(launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey]){
  266. // NSLog(@"打开方式 UniversalLinks打开");
  267. // }else if(launchOptions[UIApplicationLaunchOptionsURLKey]){
  268. // //我们需要在此处处理通过 scheme 打开App并截获参数。
  269. // NSURL *url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
  270. // NSLog(@"打开方式 通过URL打开的 ===== >> %@",url);
  271. // IOSPlatformSDK * sdk = [IOSPlatformSDK sharedInstance];
  272. // [sdk startWithUrl:url];
  273. // }else if (!launchOptions){
  274. // NSLog(@"打开方式 手动点击打开");
  275. // [IOSPlatformSDK sharedInstance];
  276. // }
  277. return YES;
  278. }
  279. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
  280. {
  281. if ([keyPath isEqual: @"outputVolume"])
  282. {
  283. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  284. }
  285. }
  286. - (void)applicationDidEnterBackground:(UIApplication*)application
  287. {
  288. ::printf("-> applicationDidEnterBackground()\n");
  289. }
  290. - (void)applicationWillEnterForeground:(UIApplication*)application
  291. {
  292. ::printf("-> applicationWillEnterForeground()\n");
  293. // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
  294. if (_unityAppReady)
  295. {
  296. // if we were showing video before going to background - the view size may be changed while we are in background
  297. [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
  298. }
  299. }
  300. - (void)applicationDidBecomeActive:(UIApplication*)application
  301. {
  302. ::printf("-> applicationDidBecomeActive()\n");
  303. [self removeSnapshotView];
  304. if (_unityAppReady)
  305. {
  306. if (UnityIsPaused() && _wasPausedExternal == false)
  307. {
  308. UnityWillResume();
  309. UnityPause(0);
  310. }
  311. if (_wasPausedExternal)
  312. {
  313. if (UnityIsFullScreenPlaying())
  314. TryResumeFullScreenVideo();
  315. }
  316. // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
  317. [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
  318. UnitySetPlayerFocus(1);
  319. }
  320. else if (!_startUnityScheduled)
  321. {
  322. _startUnityScheduled = true;
  323. [self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
  324. }
  325. _didResignActive = false;
  326. }
  327. - (void)updateUnityAudioOutput
  328. {
  329. UnityUpdateAudioOutputState();
  330. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  331. }
  332. - (void)removeSnapshotView
  333. {
  334. // do this on the main queue async so that if we try to create one
  335. // and remove in the same frame, this always happens after in the same queue
  336. dispatch_async(dispatch_get_main_queue(), ^{
  337. if (_snapshotView)
  338. {
  339. [_snapshotView removeFromSuperview];
  340. _snapshotView = nil;
  341. // Make sure that the keyboard input field regains focus after the application becomes active.
  342. [[KeyboardDelegate Instance] becomeFirstResponder];
  343. }
  344. });
  345. }
  346. - (void)applicationWillResignActive:(UIApplication*)application
  347. {
  348. ::printf("-> applicationWillResignActive()\n");
  349. if (_unityAppReady)
  350. {
  351. UnitySetPlayerFocus(0);
  352. _wasPausedExternal = UnityIsPaused();
  353. if (_wasPausedExternal == false)
  354. {
  355. // Pause Unity only if we don't need special background processing
  356. // otherwise batched player loop can be called to run user scripts.
  357. if (!UnityGetUseCustomAppBackgroundBehavior())
  358. {
  359. // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
  360. // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
  361. // NB: We will actually pause after the loop (when calling UnityPause).
  362. UnityWillPause();
  363. [self repaint];
  364. UnityPause(1);
  365. // this is done on the next frame so that
  366. // in the case where unity is paused while going
  367. // into the background and an input is deactivated
  368. // we don't mess with the view hierarchy while taking
  369. // a view snapshot (case 760747).
  370. dispatch_async(dispatch_get_main_queue(), ^{
  371. // if we are active again, we don't need to do this anymore
  372. if (!_didResignActive)
  373. {
  374. return;
  375. }
  376. _snapshotView = [self createSnapshotView];
  377. if (_snapshotView)
  378. [_rootView addSubview: _snapshotView];
  379. });
  380. }
  381. }
  382. }
  383. _didResignActive = true;
  384. }
  385. - (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
  386. {
  387. ::printf("WARNING -> applicationDidReceiveMemoryWarning()\n");
  388. UnityLowMemory();
  389. }
  390. - (void)applicationWillTerminate:(UIApplication*)application
  391. {
  392. ::printf("-> applicationWillTerminate()\n");
  393. // Only clean up if Unity has finished initializing, else the clean up process will crash,
  394. // this happens if the app is force closed immediately after opening it.
  395. if (_unityAppReady)
  396. {
  397. UnityCleanup();
  398. UnityCleanupTrampoline();
  399. }
  400. }
  401. - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
  402. {
  403. NSDictionary* arg = @{identifier: completionHandler};
  404. AppController_SendNotificationWithArg(kUnityHandleEventsForBackgroundURLSession, arg);
  405. }
  406. @end
  407. void AppController_SendNotification(NSString* name)
  408. {
  409. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController()];
  410. }
  411. void AppController_SendNotificationWithArg(NSString* name, id arg)
  412. {
  413. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
  414. }
  415. void AppController_SendUnityViewControllerNotification(NSString* name)
  416. {
  417. [[NSNotificationCenter defaultCenter] postNotificationName: name object: UnityGetGLViewController()];
  418. }
  419. extern "C" UIWindow* UnityGetMainWindow()
  420. {
  421. return GetAppController().mainDisplay.window;
  422. }
  423. extern "C" UIViewController* UnityGetGLViewController()
  424. {
  425. return GetAppController().rootViewController;
  426. }
  427. extern "C" UIView* UnityGetGLView()
  428. {
  429. return GetAppController().unityView;
  430. }
  431. extern "C" ScreenOrientation UnityCurrentOrientation() { return GetAppController().unityView.contentOrientation; }
  432. bool LogToNSLogHandler(LogType logType, const char* log, va_list list)
  433. {
  434. NSLogv([NSString stringWithUTF8String: log], list);
  435. return true;
  436. }
  437. static void AddNewAPIImplIfNeeded();
  438. // From https://stackoverflow.com/questions/4744826/detecting-if-ios-app-is-run-in-debugger
  439. static bool isDebuggerAttachedToConsole(void)
  440. // Returns true if the current process is being debugged (either
  441. // running under the debugger or has a debugger attached post facto).
  442. {
  443. int junk;
  444. int mib[4];
  445. struct kinfo_proc info;
  446. size_t size;
  447. // Initialize the flags so that, if sysctl fails for some bizarre
  448. // reason, we get a predictable result.
  449. info.kp_proc.p_flag = 0;
  450. // Initialize mib, which tells sysctl the info we want, in this case
  451. // we're looking for information about a specific process ID.
  452. mib[0] = CTL_KERN;
  453. mib[1] = KERN_PROC;
  454. mib[2] = KERN_PROC_PID;
  455. mib[3] = getpid();
  456. // Call sysctl.
  457. size = sizeof(info);
  458. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  459. assert(junk == 0);
  460. // We're being debugged if the P_TRACED flag is set.
  461. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  462. }
  463. void UnityInitTrampoline()
  464. {
  465. InitCrashHandling();
  466. NSString* version = [[UIDevice currentDevice] systemVersion];
  467. #define CHECK_VER(s) [version compare: s options: NSNumericSearch] != NSOrderedAscending
  468. _ios81orNewer = CHECK_VER(@"8.1"), _ios82orNewer = CHECK_VER(@"8.2"), _ios83orNewer = CHECK_VER(@"8.3");
  469. _ios90orNewer = CHECK_VER(@"9.0"), _ios91orNewer = CHECK_VER(@"9.1");
  470. _ios100orNewer = CHECK_VER(@"10.0"), _ios101orNewer = CHECK_VER(@"10.1"), _ios102orNewer = CHECK_VER(@"10.2"), _ios103orNewer = CHECK_VER(@"10.3");
  471. _ios110orNewer = CHECK_VER(@"11.0"), _ios111orNewer = CHECK_VER(@"11.1"), _ios112orNewer = CHECK_VER(@"11.2");
  472. _ios130orNewer = CHECK_VER(@"13.0");
  473. #undef CHECK_VER
  474. AddNewAPIImplIfNeeded();
  475. #if !TARGET_IPHONE_SIMULATOR
  476. // Use NSLog logging if a debugger is not attached, otherwise we write to stdout.
  477. if (!isDebuggerAttachedToConsole())
  478. UnitySetLogEntryHandler(LogToNSLogHandler);
  479. #endif
  480. }
  481. extern "C" bool UnityiOS81orNewer() { return _ios81orNewer; }
  482. extern "C" bool UnityiOS82orNewer() { return _ios82orNewer; }
  483. extern "C" bool UnityiOS90orNewer() { return _ios90orNewer; }
  484. extern "C" bool UnityiOS91orNewer() { return _ios91orNewer; }
  485. extern "C" bool UnityiOS100orNewer() { return _ios100orNewer; }
  486. extern "C" bool UnityiOS101orNewer() { return _ios101orNewer; }
  487. extern "C" bool UnityiOS102orNewer() { return _ios102orNewer; }
  488. extern "C" bool UnityiOS103orNewer() { return _ios103orNewer; }
  489. extern "C" bool UnityiOS110orNewer() { return _ios110orNewer; }
  490. extern "C" bool UnityiOS111orNewer() { return _ios111orNewer; }
  491. extern "C" bool UnityiOS112orNewer() { return _ios112orNewer; }
  492. extern "C" bool UnityiOS130orNewer() { return _ios130orNewer; }
  493. // sometimes apple adds new api with obvious fallback on older ios.
  494. // in that case we simply add these functions ourselves to simplify code
  495. static void AddNewAPIImplIfNeeded()
  496. {
  497. if (![[UIScreen class] instancesRespondToSelector: @selector(maximumFramesPerSecond)])
  498. {
  499. IMP UIScreen_MaximumFramesPerSecond_IMP = imp_implementationWithBlock(^NSInteger(id _self) {
  500. return 60;
  501. });
  502. class_replaceMethod([UIScreen class], @selector(maximumFramesPerSecond), UIScreen_MaximumFramesPerSecond_IMP, UIScreen_maximumFramesPerSecond_Enc);
  503. }
  504. if (![[UIView class] instancesRespondToSelector: @selector(safeAreaInsets)])
  505. {
  506. IMP UIView_SafeAreaInsets_IMP = imp_implementationWithBlock(^UIEdgeInsets(id _self) {
  507. return UIEdgeInsetsZero;
  508. });
  509. class_replaceMethod([UIView class], @selector(safeAreaInsets), UIView_SafeAreaInsets_IMP, UIView_safeAreaInsets_Enc);
  510. }
  511. }