Skip to content
This repository
Browse code

better bg task management

  • Loading branch information...
commit a1a5611c0535094dbb9e6b2cfdc3025ad74312bb 1 parent 3d4202e
Neil Rahilly neilrahilly authored
2  HelloMixpanel/HelloMixpanel/AppDelegate.h
@@ -31,4 +31,6 @@
31 31
32 32 @property (strong, nonatomic, retain) NSDate *startTime;
33 33
  34 +@property (nonatomic) UIBackgroundTaskIdentifier bgTask;
  35 +
34 36 @end
45 HelloMixpanel/HelloMixpanel/AppDelegate.m
@@ -43,10 +43,10 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
43 43
44 44 // Initialize the MixpanelAPI object
45 45 self.mixpanel = [Mixpanel sharedInstanceWithToken:MIXPANEL_TOKEN];
46   -
47   - // Set the upload interval to 10 seconds for demonstration purposes. This would be overkill for most applications.
48   - self.mixpanel.flushInterval = 10; // defaults to 60 seconds
49   -
  46 +
  47 + // Set the upload interval to 20 seconds for demonstration purposes. This would be overkill for most applications.
  48 + self.mixpanel.flushInterval = 20; // defaults to 60 seconds
  49 +
50 50 // Name a user in Mixpanel Streams
51 51 self.mixpanel.nameTag = @"Walter Sobchak";
52 52
@@ -69,7 +69,11 @@ - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDe
69 69 }
70 70
71 71 - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
72   - NSLog(@"Error in registration. Error: %@", err);
  72 +#if TARGET_IPHONE_SIMULATOR
  73 + NSLog(@"%@ push registration error is expected on simulator", self);
  74 +#else
  75 + NSLog(@"%@ push registration error: %@", self, err);
  76 +#endif
73 77 }
74 78
75 79 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
@@ -94,8 +98,39 @@ - (void)applicationDidBecomeActive:(UIApplication *)application
94 98
95 99 - (void)applicationWillResignActive:(UIApplication *)application
96 100 {
  101 + NSLog(@"%@ will resign active", self);
97 102 NSNumber *seconds = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSinceDate:self.startTime]];
98 103 [[Mixpanel sharedInstance] track:@"Session" properties:[NSDictionary dictionaryWithObject:seconds forKey:@"Length"]];
99 104 }
100 105
  106 +#pragma mark * Background task tracking test
  107 +
  108 +- (void)applicationDidEnterBackground:(UIApplication *)application
  109 +{
  110 + self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  111 +
  112 + NSLog(@"%@ background task cut short", self);
  113 +
  114 + [application endBackgroundTask:self.bgTask];
  115 + self.bgTask = UIBackgroundTaskInvalid;
  116 + }];
  117 +
  118 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  119 +
  120 + NSLog(@"%@ background task starting", self);
  121 +
  122 + // track some events and set some people properties
  123 + Mixpanel *mixpanel = [Mixpanel sharedInstance];
  124 + [mixpanel registerSuperProperties:[NSDictionary dictionaryWithObject:@"Hi!" forKey:@"Background Super Property"]];
  125 + [mixpanel track:@"Background Event"];
  126 + [mixpanel.people set:@"Background Property" to:[NSDate date]];
  127 +
  128 + [application endBackgroundTask:self.bgTask];
  129 + self.bgTask = UIBackgroundTaskInvalid;
  130 + });
  131 +
  132 + NSLog(@"%@ background task dispatched", self);
  133 +
  134 +}
  135 +
101 136 @end
63 Mixpanel/Mixpanel.m
@@ -125,10 +125,14 @@ + (NSString *)appVersion
125 125
126 126 + (BOOL)inBackground
127 127 {
  128 + BOOL inBg = NO;
128 129 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
129   - return [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground;
  130 + inBg = [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground;
130 131 #endif
131   - return false;
  132 + if (inBg) {
  133 + DevLog(@"%@ in background", self);
  134 + }
  135 + return inBg;
132 136 }
133 137
134 138 + (NSDictionary *)interfaces
@@ -430,6 +434,7 @@ - (void)startFlushTimer
430 434 selector:@selector(flush)
431 435 userInfo:nil
432 436 repeats:YES];
  437 + DevLog(@"%@ started flush timer: %@", self, self.timer);
433 438 }
434 439 }
435 440 }
@@ -439,6 +444,7 @@ - (void)stopFlushTimer
439 444 @synchronized(self) {
440 445 if (self.timer) {
441 446 [self.timer invalidate];
  447 + DevLog(@"%@ stopped flush timer: %@", self, self.timer);
442 448 }
443 449 self.timer = nil;
444 450 }
@@ -473,10 +479,10 @@ - (void)flushEvents
473 479 NSString *data = [Mixpanel encodeAPIData:self.eventsBatch];
474 480 NSString *postBody = [NSString stringWithFormat:@"ip=1&data=%@", data];
475 481
476   - self.eventsConnection = [self apiConnectionWithEndpoint:@"/track/" andBody:postBody];
477   -
478 482 DevLog(@"%@ flushing %u of %u queued events: %@", self, self.eventsBatch.count, self.eventsQueue.count, self.eventsQueue);
479 483
  484 + self.eventsConnection = [self apiConnectionWithEndpoint:@"/track/" andBody:postBody];
  485 +
480 486 [self updateNetworkActivityIndicator];
481 487 }
482 488
@@ -494,10 +500,10 @@ - (void)flushPeople
494 500 NSString *data = [Mixpanel encodeAPIData:self.peopleBatch];
495 501 NSString *postBody = [NSString stringWithFormat:@"data=%@", data];
496 502
  503 + DevLog(@"%@ flushing %u of %u queued people: %@", self, self.peopleBatch.count, self.peopleQueue.count, self.peopleQueue);
  504 +
497 505 self.peopleConnection = [self apiConnectionWithEndpoint:@"/engage/" andBody:postBody];
498 506
499   - DevLog(@"%@ flushing %u of %u queued people: %@", self, self.peopleBatch.count, self.peopleQueue.count, self.peopleQueue);
500   -
501 507 [self updateNetworkActivityIndicator];
502 508 }
503 509
@@ -606,7 +612,7 @@ - (void)unarchivePeople
606 612 NSString *filePath = [self peopleFilePath];
607 613 @try {
608 614 self.peopleQueue = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
609   - DevLog(@"%@ unarchived people data: %@", self, self.eventsQueue);
  615 + DevLog(@"%@ unarchived people data: %@", self, self.peopleQueue);
610 616 }
611 617 @catch (NSException *exception) {
612 618 NSLog(@"%@ unable to unarchive people data, starting fresh", self);
@@ -701,28 +707,32 @@ - (void)applicationWillResignActive:(NSNotification *)notification
701 707 - (void)applicationDidEnterBackground:(NSNotificationCenter *)notification
702 708 {
703 709 DevLog(@"%@ did enter background", self);
  710 +
704 711 @synchronized(self) {
  712 +
705 713 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
706   - if (self.flushOnBackground) {
707   - DevLog(@"%@ background flush turned on", self);
708   - if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)] &&
709   - [[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)]) {
710   - DevLog(@"%@ background task supported", self);
711   - self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
712   - DevLog(@"%@ background task expiration handler", self);
713   - [self.eventsConnection cancel];
714   - [self.peopleConnection cancel];
715   - self.eventsConnection = nil;
716   - self.peopleConnection = nil;
717   - [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
718   - self.taskId = UIBackgroundTaskInvalid;
719   - }];
  714 + if (self.flushOnBackground &&
  715 + [[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)] &&
  716 + [[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)]) {
  717 +
  718 + self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  719 + DevLog(@"%@ background flush cut short", self);
  720 + [self.eventsConnection cancel];
  721 + [self.peopleConnection cancel];
  722 + self.eventsConnection = nil;
  723 + self.peopleConnection = nil;
  724 + [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
  725 + self.taskId = UIBackgroundTaskInvalid;
  726 + }];
  727 +
  728 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  729 + DevLog(@"%@ background flush starting", self);
720 730 [self flush];
721   - } else {
722   - DevLog(@"%@ background task not supported", self);
723   - }
724   - } else {
725   - DevLog(@"%@ background flush turned off", self);
  731 + [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
  732 + self.taskId = UIBackgroundTaskInvalid;
  733 + });
  734 +
  735 + DevLog(@"%@ background flush dispatched", self);
726 736 }
727 737 #endif
728 738 }
@@ -784,7 +794,6 @@ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLRe
784 794 {
785 795 DevLog(@"%@ http status code: %d", self, [response statusCode]);
786 796 if ([response statusCode] != 200) {
787   - // TODO better failure message here
788 797 NSLog(@"%@ http error: %@", self, [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
789 798 } else if (connection == self.eventsConnection) {
790 799 self.eventsResponseData = [NSMutableData data];

0 comments on commit a1a5611

Please sign in to comment.
Something went wrong with that request. Please try again.