GDTCORPlatform.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 (@available(iOS 12.0, *)) {
  118. NSDictionary<NSString *, NSString *> *networkCurrentRadioAccessTechnologyDict =
  119. networkInfo.serviceCurrentRadioAccessTechnology;
  120. if (networkCurrentRadioAccessTechnologyDict.count) {
  121. // In iOS 12, multiple radio technologies can be captured. We prefer not particular radio
  122. // tech to another, so we'll just return the first value in the dictionary.
  123. networkCurrentRadioAccessTechnology = networkCurrentRadioAccessTechnologyDict.allValues[0];
  124. }
  125. } else {
  126. networkCurrentRadioAccessTechnology = networkInfo.currentRadioAccessTechnology;
  127. }
  128. #endif // TARGET_OS_MACCATALYST
  129. if (networkCurrentRadioAccessTechnology) {
  130. NSNumber *networkMobileSubtype =
  131. CTRadioAccessTechnologyToNetworkSubTypeMessage[networkCurrentRadioAccessTechnology];
  132. return networkMobileSubtype.intValue;
  133. } else {
  134. return GDTCORNetworkMobileSubtypeUNKNOWN;
  135. }
  136. #else
  137. return GDTCORNetworkMobileSubtypeUNKNOWN;
  138. #endif
  139. }
  140. NSString *_Nonnull GDTCORDeviceModel() {
  141. static NSString *deviceModel = @"Unknown";
  142. #if TARGET_OS_IOS || TARGET_OS_TV
  143. static dispatch_once_t onceToken;
  144. dispatch_once(&onceToken, ^{
  145. size_t size;
  146. char *keyToExtract = "hw.machine";
  147. sysctlbyname(keyToExtract, NULL, &size, NULL, 0);
  148. if (size > 0) {
  149. char *machine = calloc(1, size);
  150. sysctlbyname(keyToExtract, machine, &size, NULL, 0);
  151. deviceModel = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
  152. free(machine);
  153. } else {
  154. deviceModel = [UIDevice currentDevice].model;
  155. }
  156. });
  157. #endif
  158. return deviceModel;
  159. }
  160. NSData *_Nullable GDTCOREncodeArchive(id<NSSecureCoding> obj,
  161. NSString *filePath,
  162. NSError *_Nullable *error) {
  163. BOOL result = NO;
  164. if (filePath.length > 0) {
  165. result = [[NSFileManager defaultManager]
  166. createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
  167. withIntermediateDirectories:YES
  168. attributes:nil
  169. error:error];
  170. if (result == NO || *error) {
  171. GDTCORLogDebug(@"Attempt to create directory failed: path:%@ error:%@", filePath, *error);
  172. return nil;
  173. }
  174. }
  175. NSData *resultData;
  176. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4, *)) {
  177. resultData = [NSKeyedArchiver archivedDataWithRootObject:obj
  178. requiringSecureCoding:YES
  179. error:error];
  180. if (resultData == nil || (error != NULL && *error != nil)) {
  181. GDTCORLogDebug(@"Encoding an object failed: %@", *error);
  182. return nil;
  183. }
  184. if (filePath.length > 0) {
  185. result = [resultData writeToFile:filePath options:NSDataWritingAtomic error:error];
  186. if (result == NO || *error) {
  187. GDTCORLogDebug(@"Attempt to write archive failed: path:%@ error:%@", filePath, *error);
  188. } else {
  189. GDTCORLogDebug(@"Writing archive succeeded: %@", filePath);
  190. }
  191. }
  192. } else {
  193. @try {
  194. #pragma clang diagnostic push
  195. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  196. resultData = [NSKeyedArchiver archivedDataWithRootObject:obj];
  197. #pragma clang diagnostic pop
  198. if (filePath.length > 0) {
  199. result = [resultData writeToFile:filePath options:NSDataWritingAtomic error:error];
  200. if (result == NO || *error) {
  201. GDTCORLogDebug(@"Attempt to write archive failed: URL:%@ error:%@", filePath, *error);
  202. } else {
  203. GDTCORLogDebug(@"Writing archive succeeded: %@", filePath);
  204. }
  205. }
  206. } @catch (NSException *exception) {
  207. NSString *errorString =
  208. [NSString stringWithFormat:@"An exception was thrown during encoding: %@", exception];
  209. *error = [NSError errorWithDomain:NSCocoaErrorDomain
  210. code:-1
  211. userInfo:@{NSLocalizedFailureReasonErrorKey : errorString}];
  212. }
  213. GDTCORLogDebug(@"Attempt to write archive. successful:%@ URL:%@ error:%@",
  214. result ? @"YES" : @"NO", filePath, *error);
  215. }
  216. return resultData;
  217. }
  218. id<NSSecureCoding> _Nullable GDTCORDecodeArchive(Class archiveClass,
  219. NSString *_Nullable archivePath,
  220. NSData *_Nullable archiveData,
  221. NSError *_Nullable *error) {
  222. id<NSSecureCoding> unarchivedObject = nil;
  223. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4, *)) {
  224. NSData *data = archiveData ? archiveData : [NSData dataWithContentsOfFile:archivePath];
  225. if (data) {
  226. unarchivedObject = [NSKeyedUnarchiver unarchivedObjectOfClass:archiveClass
  227. fromData:data
  228. error:error];
  229. }
  230. } else {
  231. @try {
  232. NSData *archivedData =
  233. archiveData ? archiveData : [NSData dataWithContentsOfFile:archivePath];
  234. #pragma clang diagnostic push
  235. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  236. unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
  237. #pragma clang diagnostic pop
  238. } @catch (NSException *exception) {
  239. NSString *errorString =
  240. [NSString stringWithFormat:@"An exception was thrown during encoding: %@", exception];
  241. *error = [NSError errorWithDomain:NSCocoaErrorDomain
  242. code:-1
  243. userInfo:@{NSLocalizedFailureReasonErrorKey : errorString}];
  244. }
  245. }
  246. return unarchivedObject;
  247. }
  248. BOOL GDTCORWriteDataToFile(NSData *data, NSString *filePath, NSError *_Nullable *outError) {
  249. BOOL result = NO;
  250. if (filePath.length > 0) {
  251. result = [[NSFileManager defaultManager]
  252. createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
  253. withIntermediateDirectories:YES
  254. attributes:nil
  255. error:outError];
  256. if (result == NO || *outError) {
  257. GDTCORLogDebug(@"Attempt to create directory failed: path:%@ error:%@", filePath, *outError);
  258. return result;
  259. }
  260. }
  261. if (filePath.length > 0) {
  262. result = [data writeToFile:filePath options:NSDataWritingAtomic error:outError];
  263. if (result == NO || *outError) {
  264. GDTCORLogDebug(@"Attempt to write archive failed: path:%@ error:%@", filePath, *outError);
  265. } else {
  266. GDTCORLogDebug(@"Writing archive succeeded: %@", filePath);
  267. }
  268. }
  269. return result;
  270. }
  271. @interface GDTCORApplication ()
  272. /**
  273. Private flag to match the existing `readonly` public flag. This will be accurate for all platforms,
  274. since we handle each platform's lifecycle notifications separately.
  275. */
  276. @property(atomic, readwrite) BOOL isRunningInBackground;
  277. @end
  278. @implementation GDTCORApplication
  279. #if TARGET_OS_WATCH
  280. /** A dispatch queue on which all task semaphores will populate and remove from
  281. * gBackgroundIdentifierToSemaphoreMap.
  282. */
  283. static dispatch_queue_t gSemaphoreQueue;
  284. /** For mapping backgroundIdentifier to task semaphore. */
  285. static NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *gBackgroundIdentifierToSemaphoreMap;
  286. #endif
  287. + (void)load {
  288. GDTCORLogDebug(
  289. @"%@", @"GDT is initializing. Please note that if you quit the app via the "
  290. "debugger and not through a lifecycle event, event data will remain on disk but "
  291. "storage won't have a reference to them since the singleton wasn't saved to disk.");
  292. #if TARGET_OS_IOS || TARGET_OS_TV
  293. // If this asserts, please file a bug at https://github.com/firebase/firebase-ios-sdk/issues.
  294. GDTCORFatalAssert(
  295. GDTCORBackgroundIdentifierInvalid == UIBackgroundTaskInvalid,
  296. @"GDTCORBackgroundIdentifierInvalid and UIBackgroundTaskInvalid should be the same.");
  297. #endif
  298. [self sharedApplication];
  299. }
  300. + (void)initialize {
  301. #if TARGET_OS_WATCH
  302. static dispatch_once_t onceToken;
  303. dispatch_once(&onceToken, ^{
  304. gSemaphoreQueue = dispatch_queue_create("com.google.GDTCORApplication", DISPATCH_QUEUE_SERIAL);
  305. GDTCORLogDebug(
  306. @"%@",
  307. @"GDTCORApplication is initializing on watchOS, gSemaphoreQueue has been initialized.");
  308. gBackgroundIdentifierToSemaphoreMap = [[NSMutableDictionary alloc] init];
  309. GDTCORLogDebug(@"%@", @"GDTCORApplication is initializing on watchOS, "
  310. @"gBackgroundIdentifierToSemaphoreMap has been initialized.");
  311. });
  312. #endif
  313. }
  314. + (nullable GDTCORApplication *)sharedApplication {
  315. static GDTCORApplication *application;
  316. static dispatch_once_t onceToken;
  317. dispatch_once(&onceToken, ^{
  318. application = [[GDTCORApplication alloc] init];
  319. });
  320. return application;
  321. }
  322. - (instancetype)init {
  323. self = [super init];
  324. if (self) {
  325. // This class will be instantiated in the foreground.
  326. _isRunningInBackground = NO;
  327. #if TARGET_OS_IOS || TARGET_OS_TV
  328. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  329. [notificationCenter addObserver:self
  330. selector:@selector(iOSApplicationDidEnterBackground:)
  331. name:UIApplicationDidEnterBackgroundNotification
  332. object:nil];
  333. [notificationCenter addObserver:self
  334. selector:@selector(iOSApplicationWillEnterForeground:)
  335. name:UIApplicationWillEnterForegroundNotification
  336. object:nil];
  337. NSString *name = UIApplicationWillTerminateNotification;
  338. [notificationCenter addObserver:self
  339. selector:@selector(iOSApplicationWillTerminate:)
  340. name:name
  341. object:nil];
  342. #if defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  343. if (@available(iOS 13, tvOS 13.0, *)) {
  344. [notificationCenter addObserver:self
  345. selector:@selector(iOSApplicationWillEnterForeground:)
  346. name:UISceneWillEnterForegroundNotification
  347. object:nil];
  348. [notificationCenter addObserver:self
  349. selector:@selector(iOSApplicationDidEnterBackground:)
  350. name:UISceneWillDeactivateNotification
  351. object:nil];
  352. }
  353. #endif // defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  354. #elif TARGET_OS_OSX
  355. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  356. [notificationCenter addObserver:self
  357. selector:@selector(macOSApplicationWillTerminate:)
  358. name:NSApplicationWillTerminateNotification
  359. object:nil];
  360. #elif TARGET_OS_WATCH
  361. // TODO: Notification on watchOS platform is currently posted by strings which are frangible.
  362. // TODO: Needs improvements here.
  363. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  364. [notificationCenter addObserver:self
  365. selector:@selector(iOSApplicationDidEnterBackground:)
  366. name:@"UIApplicationDidEnterBackgroundNotification"
  367. object:nil];
  368. [notificationCenter addObserver:self
  369. selector:@selector(iOSApplicationWillEnterForeground:)
  370. name:@"UIApplicationWillEnterForegroundNotification"
  371. object:nil];
  372. // Adds observers for app extension on watchOS platform
  373. [notificationCenter addObserver:self
  374. selector:@selector(iOSApplicationDidEnterBackground:)
  375. name:NSExtensionHostDidEnterBackgroundNotification
  376. object:nil];
  377. [notificationCenter addObserver:self
  378. selector:@selector(iOSApplicationWillEnterForeground:)
  379. name:NSExtensionHostWillEnterForegroundNotification
  380. object:nil];
  381. #endif
  382. }
  383. return self;
  384. }
  385. #if TARGET_OS_WATCH
  386. /** Generates and maps a unique background identifier to the given semaphore.
  387. *
  388. * @param semaphore The semaphore to map.
  389. * @return A unique GDTCORBackgroundIdentifier mapped to the given semaphore.
  390. */
  391. + (GDTCORBackgroundIdentifier)createAndMapBackgroundIdentifierToSemaphore:
  392. (dispatch_semaphore_t)semaphore {
  393. __block GDTCORBackgroundIdentifier bgID = GDTCORBackgroundIdentifierInvalid;
  394. dispatch_queue_t queue = gSemaphoreQueue;
  395. NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *map = gBackgroundIdentifierToSemaphoreMap;
  396. if (queue && map) {
  397. dispatch_sync(queue, ^{
  398. bgID = arc4random();
  399. NSNumber *bgIDNumber = @(bgID);
  400. while (bgID == GDTCORBackgroundIdentifierInvalid || map[bgIDNumber]) {
  401. bgID = arc4random();
  402. bgIDNumber = @(bgID);
  403. }
  404. map[bgIDNumber] = semaphore;
  405. });
  406. }
  407. return bgID;
  408. }
  409. /** Returns the semaphore mapped to given bgID and removes the value from the map.
  410. *
  411. * @param bgID The unique NSUInteger as GDTCORBackgroundIdentifier.
  412. * @return The semaphore mapped by given bgID.
  413. */
  414. + (dispatch_semaphore_t)semaphoreForBackgroundIdentifier:(GDTCORBackgroundIdentifier)bgID {
  415. __block dispatch_semaphore_t semaphore;
  416. dispatch_queue_t queue = gSemaphoreQueue;
  417. NSMutableDictionary<NSNumber *, dispatch_semaphore_t> *map = gBackgroundIdentifierToSemaphoreMap;
  418. NSNumber *bgIDNumber = @(bgID);
  419. if (queue && map) {
  420. dispatch_sync(queue, ^{
  421. semaphore = map[bgIDNumber];
  422. [map removeObjectForKey:bgIDNumber];
  423. });
  424. }
  425. return semaphore;
  426. }
  427. #endif
  428. - (GDTCORBackgroundIdentifier)beginBackgroundTaskWithName:(NSString *)name
  429. expirationHandler:(void (^)(void))handler {
  430. __block GDTCORBackgroundIdentifier bgID = GDTCORBackgroundIdentifierInvalid;
  431. #if !TARGET_OS_WATCH
  432. bgID = [[self sharedApplicationForBackgroundTask] beginBackgroundTaskWithName:name
  433. expirationHandler:handler];
  434. #if !NDEBUG
  435. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  436. GDTCORLogDebug(@"Creating background task with name:%@ bgID:%ld", name, (long)bgID);
  437. }
  438. #endif // !NDEBUG
  439. #elif TARGET_OS_WATCH
  440. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  441. bgID = [GDTCORApplication createAndMapBackgroundIdentifierToSemaphore:semaphore];
  442. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  443. GDTCORLogDebug(@"Creating activity with name:%@ bgID:%ld on watchOS.", name, (long)bgID);
  444. }
  445. [[self sharedNSProcessInfoForBackgroundTask]
  446. performExpiringActivityWithReason:name
  447. usingBlock:^(BOOL expired) {
  448. if (expired) {
  449. if (handler) {
  450. handler();
  451. }
  452. dispatch_semaphore_signal(semaphore);
  453. GDTCORLogDebug(
  454. @"Activity with name:%@ bgID:%ld on watchOS is expiring.",
  455. name, (long)bgID);
  456. } else {
  457. dispatch_semaphore_wait(
  458. semaphore,
  459. dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC));
  460. }
  461. }];
  462. #endif
  463. return bgID;
  464. }
  465. - (void)endBackgroundTask:(GDTCORBackgroundIdentifier)bgID {
  466. #if !TARGET_OS_WATCH
  467. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  468. GDTCORLogDebug(@"Ending background task with ID:%ld was successful", (long)bgID);
  469. [[self sharedApplicationForBackgroundTask] endBackgroundTask:bgID];
  470. return;
  471. }
  472. #elif TARGET_OS_WATCH
  473. if (bgID != GDTCORBackgroundIdentifierInvalid) {
  474. dispatch_semaphore_t semaphore = [GDTCORApplication semaphoreForBackgroundIdentifier:bgID];
  475. GDTCORLogDebug(@"Ending activity with bgID:%ld on watchOS.", (long)bgID);
  476. if (semaphore) {
  477. dispatch_semaphore_signal(semaphore);
  478. GDTCORLogDebug(@"Signaling semaphore with bgID:%ld on watchOS.", (long)bgID);
  479. } else {
  480. GDTCORLogDebug(@"Semaphore with bgID:%ld is nil on watchOS.", (long)bgID);
  481. }
  482. }
  483. #endif // !TARGET_OS_WATCH
  484. }
  485. #pragma mark - App environment helpers
  486. - (BOOL)isAppExtension {
  487. BOOL appExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"];
  488. return appExtension;
  489. }
  490. /** Returns a UIApplication or NSProcessInfo instance if on the appropriate platform.
  491. *
  492. * @return The shared UIApplication or NSProcessInfo if on the appropriate platform.
  493. */
  494. #if TARGET_OS_IOS || TARGET_OS_TV
  495. - (nullable UIApplication *)sharedApplicationForBackgroundTask {
  496. #elif TARGET_OS_WATCH
  497. - (nullable NSProcessInfo *)sharedNSProcessInfoForBackgroundTask {
  498. #else
  499. - (nullable id)sharedApplicationForBackgroundTask {
  500. #endif
  501. id sharedInstance = nil;
  502. #if TARGET_OS_IOS || TARGET_OS_TV
  503. if (![self isAppExtension]) {
  504. Class uiApplicationClass = NSClassFromString(@"UIApplication");
  505. if (uiApplicationClass &&
  506. [uiApplicationClass respondsToSelector:(NSSelectorFromString(@"sharedApplication"))]) {
  507. sharedInstance = [uiApplicationClass sharedApplication];
  508. }
  509. }
  510. #elif TARGET_OS_WATCH
  511. sharedInstance = [NSProcessInfo processInfo];
  512. #endif
  513. return sharedInstance;
  514. }
  515. #pragma mark - UIApplicationDelegate and WKExtensionDelegate
  516. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  517. - (void)iOSApplicationDidEnterBackground:(NSNotification *)notif {
  518. _isRunningInBackground = YES;
  519. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  520. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is backgrounding.");
  521. [notifCenter postNotificationName:kGDTCORApplicationDidEnterBackgroundNotification object:nil];
  522. }
  523. - (void)iOSApplicationWillEnterForeground:(NSNotification *)notif {
  524. _isRunningInBackground = NO;
  525. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  526. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is foregrounding.");
  527. [notifCenter postNotificationName:kGDTCORApplicationWillEnterForegroundNotification object:nil];
  528. }
  529. #endif // TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  530. #pragma mark - UIApplicationDelegate
  531. #if TARGET_OS_IOS || TARGET_OS_TV
  532. - (void)iOSApplicationWillTerminate:(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_IOS || TARGET_OS_TV
  538. #pragma mark - NSApplicationDelegate
  539. #if TARGET_OS_OSX
  540. - (void)macOSApplicationWillTerminate:(NSNotification *)notif {
  541. NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
  542. GDTCORLogDebug(@"%@", @"GDTCORPlatform is sending a notif that the app is terminating.");
  543. [notifCenter postNotificationName:kGDTCORApplicationWillTerminateNotification object:nil];
  544. }
  545. #endif // TARGET_OS_OSX
  546. @end