GDTCORPlatform.m 24 KB

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