GDTCORPlatform.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "GoogleDataTransport/GDTCORLibrary/Public/GoogleDataTransport/GDTCORPlatform.h"
  17. #import <sys/sysctl.h>
  18. #import "GoogleDataTransport/GDTCORLibrary/Public/GoogleDataTransport/GDTCORAssert.h"
  19. #import "GoogleDataTransport/GDTCORLibrary/Public/GoogleDataTransport/GDTCORConsoleLogger.h"
  20. #import "GoogleDataTransport/GDTCORLibrary/Public/GoogleDataTransport/GDTCORReachability.h"
  21. #import "GoogleDataTransport/GDTCORLibrary/Private/GDTCORRegistrar_Private.h"
  22. #ifdef GDTCOR_VERSION
  23. #define STR(x) STR_EXPAND(x)
  24. #define STR_EXPAND(x) #x
  25. NSString *const kGDTCORVersion = @STR(GDTCOR_VERSION);
  26. #else
  27. NSString *const kGDTCORVersion = @"Unknown";
  28. #endif // GDTCOR_VERSION
  29. const GDTCORBackgroundIdentifier GDTCORBackgroundIdentifierInvalid = 0;
  30. NSString *const kGDTCORApplicationDidEnterBackgroundNotification =
  31. @"GDTCORApplicationDidEnterBackgroundNotification";
  32. NSString *const kGDTCORApplicationWillEnterForegroundNotification =
  33. @"GDTCORApplicationWillEnterForegroundNotification";
  34. NSString *const kGDTCORApplicationWillTerminateNotification =
  35. @"GDTCORApplicationWillTerminateNotification";
  36. NSURL *GDTCORRootDirectory(void) {
  37. static NSURL *GDTPath;
  38. static dispatch_once_t onceToken;
  39. dispatch_once(&onceToken, ^{
  40. NSString *cachePath =
  41. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  42. GDTPath =
  43. [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/google-sdks-events", cachePath]];
  44. GDTCORLogDebug(@"GDT's state will be saved to: %@", GDTPath);
  45. });
  46. NSError *error;
  47. [[NSFileManager defaultManager] createDirectoryAtPath:GDTPath.path
  48. withIntermediateDirectories:YES
  49. attributes:nil
  50. error:&error];
  51. GDTCORAssert(error == nil, @"There was an error creating GDT's path");
  52. return GDTPath;
  53. }
  54. BOOL GDTCORReachabilityFlagsReachable(GDTCORNetworkReachabilityFlags flags) {
  55. #if !TARGET_OS_WATCH
  56. BOOL reachable =
  57. (flags & kSCNetworkReachabilityFlagsReachable) == kSCNetworkReachabilityFlagsReachable;
  58. BOOL connectionRequired = (flags & kSCNetworkReachabilityFlagsConnectionRequired) ==
  59. kSCNetworkReachabilityFlagsConnectionRequired;
  60. return reachable && !connectionRequired;
  61. #else
  62. return (flags & kGDTCORNetworkReachabilityFlagsReachable) ==
  63. kGDTCORNetworkReachabilityFlagsReachable;
  64. #endif
  65. }
  66. BOOL GDTCORReachabilityFlagsContainWWAN(GDTCORNetworkReachabilityFlags flags) {
  67. #if TARGET_OS_IOS
  68. return (flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN;
  69. #else
  70. // Assume network connection not WWAN on macOS, tvOS, watchOS.
  71. return NO;
  72. #endif // TARGET_OS_IOS
  73. }
  74. GDTCORNetworkType GDTCORNetworkTypeMessage() {
  75. #if !TARGET_OS_WATCH
  76. SCNetworkReachabilityFlags reachabilityFlags = [GDTCORReachability currentFlags];
  77. if ((reachabilityFlags & kSCNetworkReachabilityFlagsReachable) ==
  78. kSCNetworkReachabilityFlagsReachable) {
  79. if (GDTCORReachabilityFlagsContainWWAN(reachabilityFlags)) {
  80. return GDTCORNetworkTypeMobile;
  81. } else {
  82. return GDTCORNetworkTypeWIFI;
  83. }
  84. }
  85. #endif
  86. return GDTCORNetworkTypeUNKNOWN;
  87. }
  88. GDTCORNetworkMobileSubtype GDTCORNetworkMobileSubTypeMessage() {
  89. #if TARGET_OS_IOS
  90. static NSDictionary<NSString *, NSNumber *> *CTRadioAccessTechnologyToNetworkSubTypeMessage;
  91. static CTTelephonyNetworkInfo *networkInfo;
  92. static dispatch_once_t onceToken;
  93. dispatch_once(&onceToken, ^{
  94. CTRadioAccessTechnologyToNetworkSubTypeMessage = @{
  95. CTRadioAccessTechnologyGPRS : @(GDTCORNetworkMobileSubtypeGPRS),
  96. CTRadioAccessTechnologyEdge : @(GDTCORNetworkMobileSubtypeEdge),
  97. CTRadioAccessTechnologyWCDMA : @(GDTCORNetworkMobileSubtypeWCDMA),
  98. CTRadioAccessTechnologyHSDPA : @(GDTCORNetworkMobileSubtypeHSDPA),
  99. CTRadioAccessTechnologyHSUPA : @(GDTCORNetworkMobileSubtypeHSUPA),
  100. CTRadioAccessTechnologyCDMA1x : @(GDTCORNetworkMobileSubtypeCDMA1x),
  101. CTRadioAccessTechnologyCDMAEVDORev0 : @(GDTCORNetworkMobileSubtypeCDMAEVDORev0),
  102. CTRadioAccessTechnologyCDMAEVDORevA : @(GDTCORNetworkMobileSubtypeCDMAEVDORevA),
  103. CTRadioAccessTechnologyCDMAEVDORevB : @(GDTCORNetworkMobileSubtypeCDMAEVDORevB),
  104. CTRadioAccessTechnologyeHRPD : @(GDTCORNetworkMobileSubtypeHRPD),
  105. CTRadioAccessTechnologyLTE : @(GDTCORNetworkMobileSubtypeLTE),
  106. };
  107. networkInfo = [[CTTelephonyNetworkInfo alloc] init];
  108. });
  109. NSString *networkCurrentRadioAccessTechnology;
  110. #if TARGET_OS_MACCATALYST
  111. NSDictionary<NSString *, NSString *> *networkCurrentRadioAccessTechnologyDict =
  112. networkInfo.serviceCurrentRadioAccessTechnology;
  113. if (networkCurrentRadioAccessTechnologyDict.count) {
  114. networkCurrentRadioAccessTechnology = networkCurrentRadioAccessTechnologyDict.allValues[0];
  115. }
  116. #else // TARGET_OS_MACCATALYST
  117. #if defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 120000
  118. if (@available(iOS 12.0, *)) {
  119. NSDictionary<NSString *, NSString *> *networkCurrentRadioAccessTechnologyDict =
  120. networkInfo.serviceCurrentRadioAccessTechnology;
  121. if (networkCurrentRadioAccessTechnologyDict.count) {
  122. // In iOS 12, multiple radio technologies can be captured. We prefer not particular radio
  123. // tech to another, so we'll just return the first value in the dictionary.
  124. networkCurrentRadioAccessTechnology = networkCurrentRadioAccessTechnologyDict.allValues[0];
  125. }
  126. } else {
  127. #else // defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 120000
  128. networkCurrentRadioAccessTechnology = networkInfo.currentRadioAccessTechnology;
  129. #endif // // defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 120000
  130. }
  131. #endif // TARGET_OS_MACCATALYST
  132. if (networkCurrentRadioAccessTechnology) {
  133. NSNumber *networkMobileSubtype =
  134. CTRadioAccessTechnologyToNetworkSubTypeMessage[networkCurrentRadioAccessTechnology];
  135. return networkMobileSubtype.intValue;
  136. } else {
  137. return GDTCORNetworkMobileSubtypeUNKNOWN;
  138. }
  139. #else
  140. return GDTCORNetworkMobileSubtypeUNKNOWN;
  141. #endif
  142. }
  143. NSString *_Nonnull GDTCORDeviceModel() {
  144. static NSString *deviceModel = @"Unknown";
  145. #if TARGET_OS_IOS || TARGET_OS_TV
  146. static dispatch_once_t onceToken;
  147. dispatch_once(&onceToken, ^{
  148. size_t size;
  149. char *keyToExtract = "hw.machine";
  150. sysctlbyname(keyToExtract, NULL, &size, NULL, 0);
  151. if (size > 0) {
  152. char *machine = calloc(1, size);
  153. sysctlbyname(keyToExtract, machine, &size, NULL, 0);
  154. deviceModel = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
  155. free(machine);
  156. } else {
  157. deviceModel = [UIDevice currentDevice].model;
  158. }
  159. });
  160. #endif
  161. return deviceModel;
  162. }
  163. NSData *_Nullable GDTCOREncodeArchive(id<NSSecureCoding> obj,
  164. NSString *filePath,
  165. NSError *_Nullable *error) {
  166. BOOL result = NO;
  167. if (filePath.length > 0) {
  168. result = [[NSFileManager defaultManager]
  169. createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
  170. withIntermediateDirectories:YES
  171. attributes:nil
  172. error:error];
  173. if (result == NO || *error) {
  174. GDTCORLogDebug(@"Attempt to create directory failed: path:%@ error:%@", filePath, *error);
  175. return nil;
  176. }
  177. }
  178. NSData *resultData;
  179. #if (defined(__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || \
  180. (defined(__MAC_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= 101300) || \
  181. (defined(__TVOS_11_0) && __TV_OS_VERSION_MAX_ALLOWED >= 110000) || \
  182. (defined(__WATCHOS_4_0) && __WATCH_OS_VERSION_MAX_ALLOWED >= 040000) || \
  183. (defined(TARGET_OS_MACCATALYST) && TARGET_OS_MACCATALYST)
  184. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4, *)) {
  185. resultData = [NSKeyedArchiver archivedDataWithRootObject:obj
  186. requiringSecureCoding:YES
  187. error:error];
  188. if (resultData == nil || (error != NULL && *error != nil)) {
  189. GDTCORLogDebug(@"Encoding an object failed: %@", *error);
  190. return nil;
  191. }
  192. if (filePath.length > 0) {
  193. result = [resultData writeToFile:filePath options:NSDataWritingAtomic error:error];
  194. if (result == NO || *error) {
  195. GDTCORLogDebug(@"Attempt to write archive failed: path:%@ error:%@", filePath, *error);
  196. } else {
  197. GDTCORLogDebug(@"Writing archive succeeded: %@", filePath);
  198. }
  199. }
  200. } else {
  201. #endif
  202. @try {
  203. #pragma clang diagnostic push
  204. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  205. resultData = [NSKeyedArchiver archivedDataWithRootObject:obj];
  206. #pragma clang diagnostic pop
  207. if (filePath.length > 0) {
  208. result = [resultData writeToFile:filePath options:NSDataWritingAtomic error:error];
  209. if (result == NO || *error) {
  210. GDTCORLogDebug(@"Attempt to write archive failed: URL:%@ error:%@", filePath, *error);
  211. } else {
  212. GDTCORLogDebug(@"Writing archive succeeded: %@", filePath);
  213. }
  214. }
  215. } @catch (NSException *exception) {
  216. NSString *errorString =
  217. [NSString stringWithFormat:@"An exception was thrown during encoding: %@", exception];
  218. *error = [NSError errorWithDomain:NSCocoaErrorDomain
  219. code:-1
  220. userInfo:@{NSLocalizedFailureReasonErrorKey : errorString}];
  221. }
  222. GDTCORLogDebug(@"Attempt to write archive. successful:%@ URL:%@ error:%@",
  223. result ? @"YES" : @"NO", filePath, *error);
  224. }
  225. return resultData;
  226. }
  227. id<NSSecureCoding> _Nullable GDTCORDecodeArchive(Class archiveClass,
  228. NSString *_Nullable archivePath,
  229. NSData *_Nullable archiveData,
  230. NSError *_Nullable *error) {
  231. id<NSSecureCoding> unarchivedObject = nil;
  232. #if (defined(__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || \
  233. (defined(__MAC_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= 101300) || \
  234. (defined(__TVOS_11_0) && __TV_OS_VERSION_MAX_ALLOWED >= 110000) || \
  235. (defined(__WATCHOS_4_0) && __WATCH_OS_VERSION_MAX_ALLOWED >= 040000) || \
  236. (defined(TARGET_OS_MACCATALYST) && TARGET_OS_MACCATALYST)
  237. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4, *)) {
  238. NSData *data = archiveData ? archiveData : [NSData dataWithContentsOfFile:archivePath];
  239. if (data) {
  240. unarchivedObject = [NSKeyedUnarchiver unarchivedObjectOfClass:archiveClass
  241. fromData:data
  242. error:error];
  243. }
  244. } else {
  245. #endif
  246. @try {
  247. NSData *archivedData =
  248. archiveData ? archiveData : [NSData dataWithContentsOfFile:archivePath];
  249. #pragma clang diagnostic push
  250. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  251. unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
  252. #pragma clang diagnostic pop
  253. } @catch (NSException *exception) {
  254. NSString *errorString =
  255. [NSString stringWithFormat:@"An exception was thrown during encoding: %@", exception];
  256. *error = [NSError errorWithDomain:NSCocoaErrorDomain
  257. code:-1
  258. userInfo:@{NSLocalizedFailureReasonErrorKey : errorString}];
  259. }
  260. }
  261. return unarchivedObject;
  262. }
  263. @interface GDTCORApplication ()
  264. /**
  265. Private flag to match the existing `readonly` public flag. This will be accurate for all platforms,
  266. since we handle each platform's lifecycle notifications separately.
  267. */
  268. @property(atomic, readwrite) BOOL isRunningInBackground;
  269. @end
  270. @implementation GDTCORApplication
  271. #if TARGET_OS_WATCH
  272. /** A dispatch queue on which all task semaphores will populate and remove from
  273. * gBackgroundIdentifierToSemaphoreMap.
  274. */
  275. static dispatch_queue_t gSemaphoreQueue;
  276. /** For mapping backgroundIdentifier to task semaphore. */
  277. static NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *gBackgroundIdentifierToSemaphoreMap;
  278. #endif
  279. + (void)load {
  280. GDTCORLogDebug(
  281. @"%@", @"GDT is initializing. Please note that if you quit the app via the "
  282. "debugger and not through a lifecycle event, event data will remain on disk but "
  283. "storage won't have a reference to them since the singleton wasn't saved to disk.");
  284. #if TARGET_OS_IOS || TARGET_OS_TV
  285. // If this asserts, please file a bug at https://github.com/firebase/firebase-ios-sdk/issues.
  286. GDTCORFatalAssert(
  287. GDTCORBackgroundIdentifierInvalid == UIBackgroundTaskInvalid,
  288. @"GDTCORBackgroundIdentifierInvalid and UIBackgroundTaskInvalid should be the same.");
  289. #endif
  290. [self sharedApplication];
  291. }
  292. + (void)initialize {
  293. #if TARGET_OS_WATCH
  294. static dispatch_once_t onceToken;
  295. dispatch_once(&onceToken, ^{
  296. gSemaphoreQueue = dispatch_queue_create("com.google.GDTCORApplication", DISPATCH_QUEUE_SERIAL);
  297. GDTCORLogDebug(
  298. @"%@",
  299. @"GDTCORApplication is initializing on watchOS, gSemaphoreQueue has been initialized.");
  300. gBackgroundIdentifierToSemaphoreMap = [[NSMutableDictionary alloc] init];
  301. GDTCORLogDebug(@"%@", @"GDTCORApplication is initializing on watchOS, "
  302. @"gBackgroundIdentifierToSemaphoreMap has been initialized.");
  303. });
  304. #endif
  305. }
  306. + (nullable GDTCORApplication *)sharedApplication {
  307. static GDTCORApplication *application;
  308. static dispatch_once_t onceToken;
  309. dispatch_once(&onceToken, ^{
  310. application = [[GDTCORApplication alloc] init];
  311. });
  312. return application;
  313. }
  314. - (instancetype)init {
  315. self = [super init];
  316. if (self) {
  317. // This class will be instantiated in the foreground.
  318. _isRunningInBackground = NO;
  319. #if TARGET_OS_IOS || TARGET_OS_TV
  320. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  321. [notificationCenter addObserver:self
  322. selector:@selector(iOSApplicationDidEnterBackground:)
  323. name:UIApplicationDidEnterBackgroundNotification
  324. object:nil];
  325. [notificationCenter addObserver:self
  326. selector:@selector(iOSApplicationWillEnterForeground:)
  327. name:UIApplicationWillEnterForegroundNotification
  328. object:nil];
  329. NSString *name = UIApplicationWillTerminateNotification;
  330. [notificationCenter addObserver:self
  331. selector:@selector(iOSApplicationWillTerminate:)
  332. name:name
  333. object:nil];
  334. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  335. if (@available(iOS 13, tvOS 13.0, *)) {
  336. [notificationCenter addObserver:self
  337. selector:@selector(iOSApplicationWillEnterForeground:)
  338. name:UISceneWillEnterForegroundNotification
  339. object:nil];
  340. [notificationCenter addObserver:self
  341. selector:@selector(iOSApplicationDidEnterBackground:)
  342. name:UISceneWillDeactivateNotification
  343. object:nil];
  344. }
  345. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  346. #elif TARGET_OS_OSX
  347. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  348. [notificationCenter addObserver:self
  349. selector:@selector(macOSApplicationWillTerminate:)
  350. name:NSApplicationWillTerminateNotification
  351. object:nil];
  352. #elif TARGET_OS_WATCH
  353. // TODO: Notification on watchOS platform is currently posted by strings which are frangible.
  354. // TODO: Needs improvements here.
  355. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  356. [notificationCenter addObserver:self
  357. selector:@selector(iOSApplicationDidEnterBackground:)
  358. name:@"UIApplicationDidEnterBackgroundNotification"
  359. object:nil];
  360. [notificationCenter addObserver:self
  361. selector:@selector(iOSApplicationWillEnterForeground:)
  362. name:@"UIApplicationWillEnterForegroundNotification"
  363. object:nil];
  364. // Adds observers for app extension on watchOS platform
  365. [notificationCenter addObserver:self
  366. selector:@selector(iOSApplicationDidEnterBackground:)
  367. name:NSExtensionHostDidEnterBackgroundNotification
  368. object:nil];
  369. [notificationCenter addObserver:self
  370. selector:@selector(iOSApplicationWillEnterForeground:)
  371. name:NSExtensionHostWillEnterForegroundNotification
  372. object:nil];
  373. #endif
  374. }
  375. return self;
  376. }
  377. #if TARGET_OS_WATCH
  378. /** Generates and maps a unique background identifier to the given semaphore.
  379. *
  380. * @param semaphore The semaphore to map.
  381. * @return A unique GDTCORBackgroundIdentifier mapped to the given semaphore.
  382. */
  383. + (GDTCORBackgroundIdentifier)createAndMapBackgroundIdentifierToSemaphore:
  384. (dispatch_semaphore_t)semaphore {
  385. __block GDTCORBackgroundIdentifier bgID = GDTCORBackgroundIdentifierInvalid;
  386. dispatch_queue_t queue = gSemaphoreQueue;
  387. NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *map = gBackgroundIdentifierToSemaphoreMap;
  388. if (queue && map) {
  389. dispatch_sync(queue, ^{
  390. bgID = arc4random();
  391. NSNumber *bgIDNumber = @(bgID);
  392. while (bgID == GDTCORBackgroundIdentifierInvalid || map[bgIDNumber]) {
  393. bgID = arc4random();
  394. bgIDNumber = @(bgID);
  395. }
  396. map[bgIDNumber] = semaphore;
  397. });
  398. }
  399. return bgID;
  400. }
  401. /** Returns the semaphore mapped to given bgID and removes the value from the map.
  402. *
  403. * @param bgID The unique NSUInteger as GDTCORBackgroundIdentifier.
  404. * @return The semaphore mapped by given bgID.
  405. */
  406. + (dispatch_semaphore_t)semaphoreForBackgroundIdentifier:(GDTCORBackgroundIdentifier)bgID {
  407. __block dispatch_semaphore_t semaphore;
  408. dispatch_queue_t queue = gSemaphoreQueue;
  409. NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *map = gBackgroundIdentifierToSemaphoreMap;
  410. NSNumber *bgIDNumber = @(bgID);
  411. if (queue && map) {
  412. dispatch_sync(queue, ^{
  413. semaphore = map[bgIDNumber];
  414. [map removeObjectForKey:bgIDNumber];
  415. });
  416. }
  417. return semaphore;
  418. }
  419. #endif
  420. - (GDTCORBackgroundIdentifier)beginBackgroundTaskWithName:(NSString *)name
  421. expirationHandler:(void (^)(void))handler {
  422. __block GDTCORBackgroundIdentifier bgID = GDTCORBackgroundIdentifierInvalid;
  423. #if !TARGET_OS_WATCH
  424. bgID = [[self sharedApplicationForBackgroundTask] beginBackgroundTaskWithName:name
  425. expirationHandler:handler];
  426. #if !NDEBUG
  427. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  428. GDTCORLogDebug(@"Creating background task with name:%@ bgID:%ld", name, (long)bgID);
  429. }
  430. #endif // !NDEBUG
  431. #elif TARGET_OS_WATCH
  432. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  433. bgID = [GDTCORApplication createAndMapBackgroundIdentifierToSemaphore:semaphore];
  434. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  435. GDTCORLogDebug(@"Creating activity with name:%@ bgID:%ld on watchOS.", name, (long)bgID);
  436. }
  437. [[self sharedNSProcessInfoForBackgroundTask]
  438. performExpiringActivityWithReason:name
  439. usingBlock:^(BOOL expired) {
  440. if (expired) {
  441. if (handler) {
  442. handler();
  443. }
  444. dispatch_semaphore_signal(semaphore);
  445. GDTCORLogDebug(
  446. @"Activity with name:%@ bgID:%ld on watchOS is expiring.",
  447. name, (long)bgID);
  448. } else {
  449. dispatch_semaphore_wait(
  450. semaphore,
  451. dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC));
  452. }
  453. }];
  454. #endif
  455. return bgID;
  456. }
  457. - (void)endBackgroundTask:(GDTCORBackgroundIdentifier)bgID {
  458. #if !TARGET_OS_WATCH
  459. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  460. GDTCORLogDebug(@"Ending background task with ID:%ld was successful", (long)bgID);
  461. [[self sharedApplicationForBackgroundTask] endBackgroundTask:bgID];
  462. return;
  463. }
  464. #elif TARGET_OS_WATCH
  465. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  466. dispatch_semaphore_t semaphore = [GDTCORApplication semaphoreForBackgroundIdentifier:bgID];
  467. GDTCORLogDebug(@"Ending activity with bgID:%ld on watchOS.", (long)bgID);
  468. if (semaphore) {
  469. dispatch_semaphore_signal(semaphore);
  470. GDTCORLogDebug(@"Signaling semaphore with bgID:%ld on watchOS.", (long)bgID);
  471. } else {
  472. GDTCORLogDebug(@"Semaphore with bgID:%ld is nil on watchOS.", (long)bgID);
  473. }
  474. }
  475. #endif // !TARGET_OS_WATCH
  476. }
  477. #pragma mark - App environment helpers
  478. - (BOOL)isAppExtension {
  479. BOOL appExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"];
  480. return appExtension;
  481. }
  482. /** Returns a UIApplication or NSProcessInfo instance if on the appropriate platform.
  483. *
  484. * @return The shared UIApplication or NSProcessInfo if on the appropriate platform.
  485. */
  486. #if TARGET_OS_IOS || TARGET_OS_TV
  487. - (nullable UIApplication *)sharedApplicationForBackgroundTask {
  488. #elif TARGET_OS_WATCH
  489. - (nullable NSProcessInfo *)sharedNSProcessInfoForBackgroundTask {
  490. #else
  491. - (nullable id)sharedApplicationForBackgroundTask {
  492. #endif
  493. id sharedInstance = nil;
  494. #if TARGET_OS_IOS || TARGET_OS_TV
  495. if (![self isAppExtension]) {
  496. Class uiApplicationClass = NSClassFromString(@"UIApplication");
  497. if (uiApplicationClass &&
  498. [uiApplicationClass respondsToSelector:(NSSelectorFromString(@"sharedApplication"))]) {
  499. sharedInstance = [uiApplicationClass sharedApplication];
  500. }
  501. }
  502. #elif TARGET_OS_WATCH
  503. sharedInstance = [NSProcessInfo processInfo];
  504. #endif
  505. return sharedInstance;
  506. }
  507. #pragma mark - UIApplicationDelegate and WKExtensionDelegate
  508. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  509. - (void)iOSApplicationDidEnterBackground:(NSNotification *)notif {
  510. _isRunningInBackground = YES;
  511. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  512. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is backgrounding.");
  513. [notifCenter postNotificationName:kGDTCORApplicationDidEnterBackgroundNotification object:nil];
  514. }
  515. - (void)iOSApplicationWillEnterForeground:(NSNotification *)notif {
  516. _isRunningInBackground = NO;
  517. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  518. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is foregrounding.");
  519. [notifCenter postNotificationName:kGDTCORApplicationWillEnterForegroundNotification object:nil];
  520. }
  521. #endif // TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  522. #pragma mark - UIApplicationDelegate
  523. #if TARGET_OS_IOS || TARGET_OS_TV
  524. - (void)iOSApplicationWillTerminate:(NSNotification *)notif {
  525. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  526. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is terminating.");
  527. [notifCenter postNotificationName:kGDTCORApplicationWillTerminateNotification object:nil];
  528. }
  529. #endif // TARGET_OS_IOS || TARGET_OS_TV
  530. #pragma mark - NSApplicationDelegate
  531. #if TARGET_OS_OSX
  532. - (void)macOSApplicationWillTerminate:(NSNotification *)notif {
  533. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  534. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is terminating.");
  535. [notifCenter postNotificationName:kGDTCORApplicationWillTerminateNotification object:nil];
  536. }
  537. #endif // TARGET_OS_OSX
  538. @end