PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/UkrBash/UkrBashAppDelegate.m

https://github.com/jamapag/UkrBash_iOS
Objective C | 318 lines | 216 code | 37 blank | 65 comment | 53 complexity | 1153d89640a50090c6064d9516313bf7 MD5 | raw file
  1. //
  2. // UkrBashAppDelegate.m
  3. // UkrBash
  4. //
  5. // Created by Maks Markovets on 9/7/11.
  6. // Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "UkrBashAppDelegate.h"
  9. #import "UBQuotesContainerController.h"
  10. #import "UBPicturesCollectionViewController.h"
  11. #import "UBMenuViewController.h"
  12. #import "UBNavigationController.h"
  13. #import "UBPublishedQuotesDataSource.h"
  14. #import "UBPublishedPicturesDataSource.h"
  15. #import "UBFetchedPicturesDataSource.h"
  16. #import "UBFavoritePicturesDataSource.h"
  17. #import "GAI.h"
  18. #import "GAIFields.h"
  19. #import "GAIDictionaryBuilder.h"
  20. #import "ApiKey.h"
  21. #import "SharingController.h"
  22. #import "FacebookSharingController.h"
  23. #import "Reachability.h"
  24. #import "Quote.h"
  25. #import "UBQuotesController.h"
  26. #import "UBPicturesController.h"
  27. #import "UBMainViewController.h"
  28. #import <sys/sysctl.h>
  29. @implementation UkrBashAppDelegate
  30. @synthesize window=_window;
  31. @synthesize managedObjectContext=__managedObjectContext;
  32. @synthesize managedObjectModel=__managedObjectModel;
  33. @synthesize persistentStoreCoordinator=__persistentStoreCoordinator;
  34. -(NSString *)deviceType {
  35. size_t size;
  36. sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  37. char *machine = malloc(size);
  38. sysctlbyname("hw.machine", machine, &size, NULL, 0);
  39. NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
  40. free(machine);
  41. if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
  42. if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
  43. if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
  44. if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
  45. if ([platform isEqualToString:@"iPhone3,3"]) return @"Verizon iPhone 4";
  46. if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
  47. if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
  48. if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 CDMA";
  49. if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5C";
  50. if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5C CDMA";
  51. if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5S";
  52. if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5S CDMA";
  53. if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
  54. if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
  55. if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
  56. if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
  57. if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
  58. if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
  59. if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
  60. if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
  61. if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
  62. if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
  63. if ([platform isEqualToString:@"iPad3,1"]) return @"iPad-3G (WiFi)";
  64. if ([platform isEqualToString:@"iPad3,2"]) return @"iPad-3G (GSM)";
  65. if ([platform isEqualToString:@"iPad3,3"]) return @"iPad-3G (CDMA)";
  66. if ([platform isEqualToString:@"iPad3,4"]) return @"iPad4Wifi";
  67. if ([platform isEqualToString:@"iPad3,5"]) return @"iPad4GSM";
  68. if ([platform isEqualToString:@"iPad3,6"]) return @"iPad4CDMA";
  69. if ([platform isEqualToString:@"i386"]) return @"Simulator";
  70. if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
  71. return platform;
  72. }
  73. - (UBCenterViewController *)containerWithType:(NSString*)type dataSource:(NSString*)dataSource
  74. {
  75. if (!type) {
  76. return [[[UBQuotesContainerController alloc] initWithDataSourceClass:[UBPublishedQuotesDataSource class]] autorelease];
  77. } else if ([type isEqualToString:UBContainerTypeQuotes]) {
  78. if (!dataSource) {
  79. dataSource = NSStringFromClass([UBPublishedQuotesDataSource class]);
  80. }
  81. if ([dataSource isEqualToString:@"UBFavoriteQuotesDataSource"]) {
  82. return [[[UBQuotesController alloc] initWithDataSourceClass:NSClassFromString(dataSource)] autorelease];
  83. }
  84. return [[[UBQuotesContainerController alloc] initWithDataSourceClass:NSClassFromString(dataSource)] autorelease];
  85. } else if ([type isEqualToString:UBContainerTypePictures]) {
  86. if (!dataSource) {
  87. dataSource = NSStringFromClass([UBPublishedPicturesDataSource class]);
  88. }
  89. if ([dataSource isEqualToString:@"UBFavoritePicturesDataSource"]) {
  90. return [[[UBPicturesController alloc] initWithDataSourceClass:NSClassFromString(dataSource)] autorelease];
  91. }
  92. return [[[UBPicturesCollectionViewController alloc] initWithDataSourceClass:NSClassFromString(dataSource)] autorelease];
  93. }
  94. return nil;
  95. }
  96. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  97. {
  98. #if TARGET_IPHONE_SIMULATOR
  99. [[GAI sharedInstance].logger setLogLevel:kGAILogLevelVerbose];
  100. #endif
  101. id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:kGANAccountID];
  102. [tracker set:[GAIFields customDimensionForIndex:1] value:[self deviceType]];
  103. [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"copying"
  104. action:@"quotes"
  105. label:@"quote"
  106. value:@(-1)] build]];
  107. [self.window makeKeyAndVisible];
  108. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  109. NSString *containerType = [userDefaults stringForKey:UBContainerTypeKey];
  110. NSString *containerTitle = [userDefaults stringForKey:UBContainerTitleKey];
  111. NSString *containerDataSource = [userDefaults stringForKey:UBContainerDataSourceKey];
  112. if (!containerTitle) {
  113. containerTitle = @"Опубліковане";
  114. }
  115. UBCenterViewController *containerController = [self containerWithType:containerType dataSource:containerDataSource];
  116. containerController.title = containerTitle;
  117. UBMainViewController *mainViewController = [[UBMainViewController alloc] initWithContainerController:containerController];
  118. self.window.rootViewController = mainViewController;
  119. [self.window addSubview:mainViewController.view];
  120. Reachability *reach = [Reachability reachabilityWithHostname:@"www.ukrbash.com"];
  121. reach.unreachableBlock = ^(Reachability *reach) {
  122. dispatch_async(dispatch_get_main_queue(), ^{
  123. NSArray *titles = @[@"Невдача!", @"От халепа!"];
  124. NSArray *messages = @[@"Щось не так зі зв`язком. Або з Інтернетом. Або із сайтом UkrBash. Або з телефоном.",
  125. @"Не вдається вийти на зв`язок. Треба перевірити налаштування інтернетів."];
  126. NSArray *buttons = @[@"Ну добре", @"OK", @"Зараз перевірю"];
  127. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[titles objectAtIndex:arc4random_uniform((u_int32_t)titles.count)]
  128. message:[messages objectAtIndex:arc4random_uniform((u_int32_t)messages.count)]
  129. delegate:nil
  130. cancelButtonTitle:[buttons objectAtIndex:arc4random_uniform((u_int32_t)buttons.count)]
  131. otherButtonTitles:nil];
  132. [alert show];
  133. [alert release];
  134. });
  135. };
  136. [reach startNotifier];
  137. return YES;
  138. }
  139. - (void)applicationWillResignActive:(UIApplication *)application
  140. {
  141. /*
  142. Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  143. Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  144. */
  145. }
  146. - (void)applicationDidEnterBackground:(UIApplication *)application
  147. {
  148. /*
  149. Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  150. If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  151. */
  152. }
  153. - (void)applicationWillEnterForeground:(UIApplication *)application
  154. {
  155. /*
  156. Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  157. */
  158. }
  159. - (void)applicationDidBecomeActive:(UIApplication *)application
  160. {
  161. /*
  162. Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  163. */
  164. }
  165. - (void)applicationWillTerminate:(UIApplication *)application
  166. {
  167. // Saves changes in the application's managed object context before the application terminates.
  168. [self saveContext];
  169. }
  170. - (void)dealloc
  171. {
  172. [_window release];
  173. [__managedObjectContext release];
  174. [__managedObjectModel release];
  175. [__persistentStoreCoordinator release];
  176. [navigationController release];
  177. [super dealloc];
  178. }
  179. - (void)saveContext
  180. {
  181. NSError *error = nil;
  182. NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
  183. if (managedObjectContext != nil)
  184. {
  185. if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
  186. {
  187. /*
  188. Replace this implementation with code to handle the error appropriately.
  189. 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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  190. */
  191. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  192. abort();
  193. }
  194. }
  195. }
  196. #pragma mark - Core Data stack
  197. /**
  198. Returns the managed object context for the application.
  199. If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
  200. */
  201. - (NSManagedObjectContext *)managedObjectContext
  202. {
  203. if (__managedObjectContext != nil)
  204. {
  205. return __managedObjectContext;
  206. }
  207. NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  208. if (coordinator != nil)
  209. {
  210. __managedObjectContext = [[NSManagedObjectContext alloc] init];
  211. [__managedObjectContext setPersistentStoreCoordinator:coordinator];
  212. }
  213. return __managedObjectContext;
  214. }
  215. /**
  216. Returns the managed object model for the application.
  217. If the model doesn't already exist, it is created from the application's model.
  218. */
  219. - (NSManagedObjectModel *)managedObjectModel
  220. {
  221. if (__managedObjectModel != nil)
  222. {
  223. return __managedObjectModel;
  224. }
  225. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"UkrBash" withExtension:@"momd"];
  226. __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  227. return __managedObjectModel;
  228. }
  229. /**
  230. Returns the persistent store coordinator for the application.
  231. If the coordinator doesn't already exist, it is created and the application's store added to it.
  232. */
  233. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
  234. {
  235. if (__persistentStoreCoordinator != nil)
  236. {
  237. return __persistentStoreCoordinator;
  238. }
  239. NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UkrBash.sqlite"];
  240. NSError *error = nil;
  241. __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  242. if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
  243. {
  244. /*
  245. Replace this implementation with code to handle the error appropriately.
  246. 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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
  247. Typical reasons for an error here include:
  248. * The persistent store is not accessible;
  249. * The schema for the persistent store is incompatible with current managed object model.
  250. Check the error message to determine what the actual problem was.
  251. 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.
  252. If you encounter schema incompatibility errors during development, you can reduce their frequency by:
  253. * Simply deleting the existing store:
  254. [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
  255. * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
  256. [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
  257. Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
  258. */
  259. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  260. abort();
  261. }
  262. return __persistentStoreCoordinator;
  263. }
  264. #pragma mark - Application's Documents directory
  265. /**
  266. Returns the URL to the application's Documents directory.
  267. */
  268. - (NSURL *)applicationDocumentsDirectory
  269. {
  270. return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  271. }
  272. @end