Skip to content
Browse files

better bg task management

  • Loading branch information...
1 parent 3d4202e commit a1a5611c0535094dbb9e6b2cfdc3025ad74312bb @neilrahilly neilrahilly committed Oct 18, 2012
Showing with 78 additions and 32 deletions.
  1. +2 −0 HelloMixpanel/HelloMixpanel/AppDelegate.h
  2. +40 −5 HelloMixpanel/HelloMixpanel/AppDelegate.m
  3. +36 −27 Mixpanel/Mixpanel.m
View
2 HelloMixpanel/HelloMixpanel/AppDelegate.h
@@ -31,4 +31,6 @@
@property (strong, nonatomic, retain) NSDate *startTime;
+@property (nonatomic) UIBackgroundTaskIdentifier bgTask;
+
@end
View
45 HelloMixpanel/HelloMixpanel/AppDelegate.m
@@ -43,10 +43,10 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
// Initialize the MixpanelAPI object
self.mixpanel = [Mixpanel sharedInstanceWithToken:MIXPANEL_TOKEN];
-
- // Set the upload interval to 10 seconds for demonstration purposes. This would be overkill for most applications.
- self.mixpanel.flushInterval = 10; // defaults to 60 seconds
-
+
+ // Set the upload interval to 20 seconds for demonstration purposes. This would be overkill for most applications.
+ self.mixpanel.flushInterval = 20; // defaults to 60 seconds
+
// Name a user in Mixpanel Streams
self.mixpanel.nameTag = @"Walter Sobchak";
@@ -69,7 +69,11 @@ - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDe
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
- NSLog(@"Error in registration. Error: %@", err);
+#if TARGET_IPHONE_SIMULATOR
+ NSLog(@"%@ push registration error is expected on simulator", self);
+#else
+ NSLog(@"%@ push registration error: %@", self, err);
+#endif
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
@@ -94,8 +98,39 @@ - (void)applicationDidBecomeActive:(UIApplication *)application
- (void)applicationWillResignActive:(UIApplication *)application
{
+ NSLog(@"%@ will resign active", self);
NSNumber *seconds = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSinceDate:self.startTime]];
[[Mixpanel sharedInstance] track:@"Session" properties:[NSDictionary dictionaryWithObject:seconds forKey:@"Length"]];
}
+#pragma mark * Background task tracking test
+
+- (void)applicationDidEnterBackground:(UIApplication *)application
+{
+ self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
+
+ NSLog(@"%@ background task cut short", self);
+
+ [application endBackgroundTask:self.bgTask];
+ self.bgTask = UIBackgroundTaskInvalid;
+ }];
+
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+
+ NSLog(@"%@ background task starting", self);
+
+ // track some events and set some people properties
+ Mixpanel *mixpanel = [Mixpanel sharedInstance];
+ [mixpanel registerSuperProperties:[NSDictionary dictionaryWithObject:@"Hi!" forKey:@"Background Super Property"]];
+ [mixpanel track:@"Background Event"];
+ [mixpanel.people set:@"Background Property" to:[NSDate date]];
+
+ [application endBackgroundTask:self.bgTask];
+ self.bgTask = UIBackgroundTaskInvalid;
+ });
+
+ NSLog(@"%@ background task dispatched", self);
+
+}
+
@end
View
63 Mixpanel/Mixpanel.m
@@ -125,10 +125,14 @@ + (NSString *)appVersion
+ (BOOL)inBackground
{
+ BOOL inBg = NO;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
- return [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground;
+ inBg = [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground;
#endif
- return false;
+ if (inBg) {
+ DevLog(@"%@ in background", self);
+ }
+ return inBg;
}
+ (NSDictionary *)interfaces
@@ -430,6 +434,7 @@ - (void)startFlushTimer
selector:@selector(flush)
userInfo:nil
repeats:YES];
+ DevLog(@"%@ started flush timer: %@", self, self.timer);
}
}
}
@@ -439,6 +444,7 @@ - (void)stopFlushTimer
@synchronized(self) {
if (self.timer) {
[self.timer invalidate];
+ DevLog(@"%@ stopped flush timer: %@", self, self.timer);
}
self.timer = nil;
}
@@ -473,10 +479,10 @@ - (void)flushEvents
NSString *data = [Mixpanel encodeAPIData:self.eventsBatch];
NSString *postBody = [NSString stringWithFormat:@"ip=1&data=%@", data];
- self.eventsConnection = [self apiConnectionWithEndpoint:@"/track/" andBody:postBody];
-
DevLog(@"%@ flushing %u of %u queued events: %@", self, self.eventsBatch.count, self.eventsQueue.count, self.eventsQueue);
+ self.eventsConnection = [self apiConnectionWithEndpoint:@"/track/" andBody:postBody];
+
[self updateNetworkActivityIndicator];
}
@@ -494,10 +500,10 @@ - (void)flushPeople
NSString *data = [Mixpanel encodeAPIData:self.peopleBatch];
NSString *postBody = [NSString stringWithFormat:@"data=%@", data];
+ DevLog(@"%@ flushing %u of %u queued people: %@", self, self.peopleBatch.count, self.peopleQueue.count, self.peopleQueue);
+
self.peopleConnection = [self apiConnectionWithEndpoint:@"/engage/" andBody:postBody];
- DevLog(@"%@ flushing %u of %u queued people: %@", self, self.peopleBatch.count, self.peopleQueue.count, self.peopleQueue);
-
[self updateNetworkActivityIndicator];
}
@@ -606,7 +612,7 @@ - (void)unarchivePeople
NSString *filePath = [self peopleFilePath];
@try {
self.peopleQueue = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
- DevLog(@"%@ unarchived people data: %@", self, self.eventsQueue);
+ DevLog(@"%@ unarchived people data: %@", self, self.peopleQueue);
}
@catch (NSException *exception) {
NSLog(@"%@ unable to unarchive people data, starting fresh", self);
@@ -701,28 +707,32 @@ - (void)applicationWillResignActive:(NSNotification *)notification
- (void)applicationDidEnterBackground:(NSNotificationCenter *)notification
{
DevLog(@"%@ did enter background", self);
+
@synchronized(self) {
+
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
- if (self.flushOnBackground) {
- DevLog(@"%@ background flush turned on", self);
- if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)] &&
- [[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)]) {
- DevLog(@"%@ background task supported", self);
- self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
- DevLog(@"%@ background task expiration handler", self);
- [self.eventsConnection cancel];
- [self.peopleConnection cancel];
- self.eventsConnection = nil;
- self.peopleConnection = nil;
- [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
- self.taskId = UIBackgroundTaskInvalid;
- }];
+ if (self.flushOnBackground &&
+ [[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)] &&
+ [[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)]) {
+
+ self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
+ DevLog(@"%@ background flush cut short", self);
+ [self.eventsConnection cancel];
+ [self.peopleConnection cancel];
+ self.eventsConnection = nil;
+ self.peopleConnection = nil;
+ [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
+ self.taskId = UIBackgroundTaskInvalid;
+ }];
+
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+ DevLog(@"%@ background flush starting", self);
[self flush];
- } else {
- DevLog(@"%@ background task not supported", self);
- }
- } else {
- DevLog(@"%@ background flush turned off", self);
+ [[UIApplication sharedApplication] endBackgroundTask:self.taskId];
+ self.taskId = UIBackgroundTaskInvalid;
+ });
+
+ DevLog(@"%@ background flush dispatched", self);
}
#endif
}
@@ -784,7 +794,6 @@ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLRe
{
DevLog(@"%@ http status code: %d", self, [response statusCode]);
if ([response statusCode] != 200) {
- // TODO better failure message here
NSLog(@"%@ http error: %@", self, [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
} else if (connection == self.eventsConnection) {
self.eventsResponseData = [NSMutableData data];

0 comments on commit a1a5611

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