shlist

share and manage lists between multiple people
Log | Files | Refs

AppDelegate.m (8599B)


      1 #import "AppDelegate.h"
      2 #import "Network.h"
      3 
      4 #import <CoreData/CoreData.h>
      5 
      6 @interface AppDelegate () {
      7 	Network *network_connection;
      8 }
      9 
     10 @end
     11 
     12 @implementation AppDelegate
     13 
     14 @synthesize managedObjectContext = _managedObjectContext;
     15 @synthesize managedObjectModel = _managedObjectModel;
     16 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
     17 
     18 - (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
     19 {
     20 	// we need to issue connect/reconnects from here
     21 	network_connection = [Network shared_network_connection];
     22 
     23 	// Register the supported interaction types.
     24 	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge];
     25 
     26 	// customization after application launch
     27 	return YES;
     28 }
     29 
     30 // Handle remote notification registration.
     31 - (void)application:(UIApplication *)app
     32 	didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken
     33 {
     34 	const unsigned char *token_data = [devToken bytes];
     35 	NSUInteger token_length = [devToken length];
     36 
     37 	NSMutableString *hex_token = [NSMutableString stringWithCapacity:(token_length * 2)];
     38 	for (int i = 0; i < token_length; i++) {
     39 		[hex_token appendFormat:@"%02lX", (unsigned long)token_data[i]];
     40 	}
     41 
     42 	NSLog(@"apn: device token is 0x%@", hex_token);
     43 	if ([network_connection get_device_id] != nil) {
     44 		[network_connection send_message:device_update contents:hex_token];
     45 	}
     46 }
     47 
     48 // Called when push notification received
     49 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
     50 {
     51 	NSLog(@"notify: got remote notification");
     52 
     53 	NSString *msg_type = userInfo[@"msg_type"];
     54 	if (msg_type == nil) {
     55 		NSLog(@"didReceiveRemoteNotification: did not have 'msg_type' key");
     56 		return;
     57 	}
     58 
     59 	// Create unique notification name based on the incoming message type
     60 	NSString *notification_name = [NSString stringWithFormat:@"PushNotification_%@", userInfo[@"msg_type"]];
     61 
     62 	if (![userInfo[@"payload"] isKindOfClass:[NSDictionary class]]) {
     63 		NSLog(@"didReceiveRemoteNotification: payload wasn't a dictionary");
     64 		return;
     65 	}
     66 
     67 	[[NSNotificationCenter defaultCenter] postNotificationName:notification_name object:nil userInfo:userInfo[@"payload"]];
     68 }
     69 
     70 - (void) applicationWillResignActive:(UIApplication *)application
     71 {
     72 	// Sent when the application is about to move from active to inactive
     73 	// state. This can occur for certain types of temporary interruptions
     74 	// (such as an incoming phone call or SMS message) or when the user
     75 	// quits the application and it begins the transition to the background
     76 	// state.
     77 	//
     78 	// Use this method to pause ongoing tasks, disable timers, and throttle
     79 	// down OpenGL ES frame rates. Games should use this method to pause the
     80 	// game.
     81 }
     82 
     83 - (void) applicationDidEnterBackground:(UIApplication *)application
     84 {
     85 	// Use this method to release shared resources, save user data,
     86 	// invalidate timers, and store enough application state information to
     87 	// restore your application to its current state in case it is
     88 	// terminated later.
     89 	// If your application supports background execution, this method is
     90 	// called instead of applicationWillTerminate: when the user quits.
     91 
     92 	NSLog(@"info: app: entering background, disconnecting network");
     93 	[network_connection disconnect];
     94 }
     95 
     96 - (void) applicationWillEnterForeground:(UIApplication *)application
     97 {
     98 	// Called as part of the transition from the background to the inactive
     99 	// state; here you can undo many of the changes made on entering the
    100 	// background.
    101 
    102 	NSLog(@"info: app: entering foreground, reconnecting...");
    103 	[network_connection connect];
    104 	//[network_connection send_message:lists_get contents:[[NSMutableDictionary alloc] init]];
    105 	//[network_connection send_message:lists_get_other contents:[[NSMutableDictionary alloc] init]];
    106 }
    107 
    108 - (void) applicationDidBecomeActive:(UIApplication *)application
    109 {
    110 	// Restart any tasks that were paused (or not yet started) while the
    111 	// application was inactive. If the application was previously in the
    112 	// background, optionally refresh the user interface.
    113 }
    114 
    115 - (void) applicationWillTerminate:(UIApplication *)application
    116 {
    117 	// Called when the application is about to terminate. Save data if
    118 	// appropriate. See also applicationDidEnterBackground:.
    119 
    120 	NSLog(@"info: app: teminating, disconnecting network");
    121 	[network_connection disconnect];
    122 }
    123 
    124 - (void)application:(UIApplication *)app
    125 	didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
    126 {
    127 	NSLog(@"Error in registration. Error: %@", err);
    128 }
    129 
    130 - (void)saveContext
    131 {
    132 	NSError *error = nil;
    133 	NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    134 	if (managedObjectContext != nil) {
    135 		if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
    136 			// Replace this implementation with code to handle the error appropriately.
    137 			// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    138 			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    139 			abort();
    140 		}
    141 	}
    142 }
    143 
    144 #pragma mark - Core Data stack
    145 
    146 // Returns the managed object context for the application.
    147 // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
    148 - (NSManagedObjectContext *)managedObjectContext
    149 {
    150 	if (_managedObjectContext != nil) {
    151 		return _managedObjectContext;
    152 	}
    153 
    154 	NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    155 	if (coordinator != nil) {
    156 		_managedObjectContext = [[NSManagedObjectContext alloc] init];
    157 		[_managedObjectContext setPersistentStoreCoordinator:coordinator];
    158 	}
    159 	return _managedObjectContext;
    160 }
    161 
    162 // Returns the managed object model for the application.
    163 // If the model doesn't already exist, it is created from the application's model.
    164 - (NSManagedObjectModel *)managedObjectModel
    165 {
    166 	if (_managedObjectModel != nil) {
    167 		return _managedObjectModel;
    168 	}
    169 	NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"shlist" withExtension:@"momd"];
    170 	_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    171 	return _managedObjectModel;
    172 }
    173 
    174 // Returns the persistent store coordinator for the application.
    175 // If the coordinator doesn't already exist, it is created and the application's store added to it.
    176 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    177 {
    178 	if (_persistentStoreCoordinator != nil) {
    179 		return _persistentStoreCoordinator;
    180 	}
    181 
    182 	NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"shlist.sqlite"];
    183 
    184 	NSError *error = nil;
    185 	_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    186 	if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    187 		/*
    188 		 Replace this implementation with code to handle the error appropriately.
    189 
    190 		 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    191 
    192 		 Typical reasons for an error here include:
    193 		 * The persistent store is not accessible;
    194 		 * The schema for the persistent store is incompatible with current managed object model.
    195 		 Check the error message to determine what the actual problem was.
    196 
    197 		 If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
    198 
    199 		 If you encounter schema incompatibility errors during development, you can reduce their frequency by:
    200 		 * Simply deleting the existing store:
    201 		 [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
    202 
    203 		 * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
    204 		 @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
    205 
    206 		 Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
    207 
    208 		 */
    209 		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    210 		abort();
    211 	}
    212 
    213 	return _persistentStoreCoordinator;
    214 }
    215 
    216 #pragma mark - Application's Documents directory
    217 
    218 // Returns the URL to the application's Documents directory.
    219 - (NSURL *)applicationDocumentsDirectory
    220 {
    221 	return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    222 }
    223 
    224 @end