AppDelegate.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //
  2. // AppDelegate.m
  3. // kneet2
  4. //
  5. // Created by Created by Jason Lee on 10/1/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "AppDelegate.h"
  10. #import "RequestHandler.h"
  11. #import "DeviceModel.h"
  12. #import <Fabric/Fabric.h>
  13. #import <Crashlytics/Crashlytics.h>
  14. @interface AppDelegate ()
  15. @end
  16. // Constants
  17. // static NSString * const kSomeLocalConstant = @"SomeValue";
  18. @implementation AppDelegate
  19. @synthesize window = _window;
  20. #pragma mark -
  21. #pragma mark Static methods
  22. #pragma mark -
  23. #pragma mark Init and dealloc
  24. #pragma mark -
  25. #pragma mark Properties
  26. #pragma mark -
  27. #pragma mark Public methods
  28. #pragma mark -
  29. #pragma mark Private methods
  30. #pragma mark -
  31. #pragma mark Delegate methods
  32. #pragma mark UIApplicationDelegate
  33. - (BOOL)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(__unused NSDictionary *)launchOptions {
  34. #ifndef PRODUCT_MODE //운영모드가 아닐 경우,
  35. [self checkLaunchOptions:launchOptions];
  36. #endif
  37. application.applicationIconBadgeNumber = 0;
  38. [self initializeApp];
  39. [self initRemoteNotification:launchOptions];
  40. return YES;
  41. }
  42. #pragma mark Handlers
  43. - (void)initializeApp {
  44. [Fabric with:@[[Crashlytics class]]];
  45. //set logger
  46. [DDLog addLogger:[DDASLLogger sharedInstance]];
  47. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  48. [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
  49. }
  50. #pragma mark - Initialize Application
  51. - (void)checkLaunchOptions:(id)launchOptions {
  52. if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]) {
  53. NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]);
  54. [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
  55. }
  56. if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
  57. NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]);
  58. [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsLocalNotificationKey"];
  59. }
  60. }
  61. #pragma mark - APNS Setting
  62. /**
  63. APNS 초기화
  64. */
  65. - (void)initRemoteNotification:(NSDictionary *)launchOptions {
  66. // APNS에 디바이스를 등록한다.
  67. #if TARGET_IPHONE_SIMULATOR
  68. [JDFacade facade].APNSToken = @"IPHONE SIMULATOR";
  69. #else
  70. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  71. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  72. [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
  73. #endif
  74. if (launchOptions) {
  75. NSDictionary *pushInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  76. if (pushInfo) {
  77. [self handlePushNotification:pushInfo];
  78. }
  79. }
  80. }
  81. // 디바이스 토큰 받는곳
  82. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  83. NSMutableString *deviceId = [NSMutableString string];
  84. const unsigned char *ptr = (const unsigned char*) [deviceToken bytes];
  85. for(int i = 0 ; i < 32 ; i++) {
  86. [deviceId appendFormat:@"%02x", ptr[i]];
  87. }
  88. //메모리에 저장.
  89. [JDFacade facade].APNSToken = deviceId;
  90. NSLog(@"APNS Device Token: %@", deviceId);
  91. }
  92. // 서버에 등록 실패했을 경우.
  93. - (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  94. {
  95. NSLog(@"didFailToRegisterForRemoteNotifications: %@", error);
  96. }
  97. // 푸시 처리
  98. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
  99. [self handlePushNotification:userInfo];
  100. }
  101. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  102. [application registerForRemoteNotifications];
  103. }
  104. - (void)handlePushNotification:(NSDictionary *)pushInfo {
  105. NSLog(@"%@", pushInfo);
  106. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  107. NSString *message = nil;
  108. NSString *pushTypeCode = [pushInfo objectForKey:@"push_type_code"];
  109. if (pushTypeCode) {
  110. message = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
  111. NSString *homegrpId = [pushInfo objectForKey:@"homegrp_id"];
  112. [self handleWithPushTypeCode:pushTypeCode dummyCode:homegrpId message:message];
  113. return;
  114. } else {
  115. message = [[pushInfo objectForKey:@"aps"] objectForKey:@"alert"];
  116. }
  117. if (message && ![message isEmptyString]) {
  118. [[JDFacade facade] alert:message];
  119. }
  120. }
  121. - (void)handleWithPushTypeCode:(NSString *)pushTypeCode dummyCode:(NSString *)dummyCode message:(NSString *)message {
  122. NSLog(@"%s\n %@, %@, %@", __PRETTY_FUNCTION__, pushTypeCode, dummyCode, message);
  123. if ([pushTypeCode isEqualToString:@"HOME_MEM_INV"]) {//홈 초대받음
  124. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  125. if (buttonIndex == 0) {
  126. [[JDFacade facade] loadInvitationView];
  127. }
  128. }];
  129. } else if ([pushTypeCode isEqualToString:@"HOME_MEM_REF"]) {//홈초대 거절 시
  130. [[JDFacade facade] alert:message];
  131. [[JDFacade facade] updateMainViewController];
  132. } else if ([pushTypeCode isEqualToString:@"HOME_MEM_BAN"]) {//홈에서 강퇴됨
  133. [[JDFacade facade] alert:message completionHander:^{
  134. [[JDFacade facade] updateMainViewController];
  135. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  136. }];
  137. } else if ([pushTypeCode isEqualToString:@"HOME_MEM_SEL"]) {//홈에서 멤버가 탈퇴함
  138. [[JDFacade facade] alert:message];
  139. [[JDFacade facade] updateMainViewController];
  140. } else if ([pushTypeCode isEqualToString:@"HOME_DEL"]) {//홈그룹 삭제
  141. [[JDFacade facade] alert:message completionHander:^{
  142. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  143. }];
  144. } else if ([pushTypeCode isEqualToString:@"DVC_CER_REV"]) {//단말 인증 해지됨
  145. [[JDFacade facade] alert:message completionHander:^{
  146. [[JDFacade facade] logout];
  147. }];
  148. } else if ([pushTypeCode isEqualToString:@"MODE_CHG"] || [pushTypeCode isEqualToString:@"MODE_CHG_ERR"]) {//홈 모드 변경 시, 홈 모드 변경 시 일부장치 제어 실패
  149. [[JDFacade facade] alert:message];
  150. } else if ([pushTypeCode isEqualToString:@"RULE_EXC"] || [pushTypeCode isEqualToString:@"RULE_ERR"]) {//규칙 실행 시, 규칙 실패 누적으로 규칙
  151. [[JDFacade facade] alert:message];
  152. } else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"DVC_OWN_CHG"]) {//홈허브 삭제됨, 장치 소유주 변경 알림 - 대시보드
  153. [[JDFacade facade] alert:message completionHander:^{
  154. [[JDFacade facade] requestPollingHomeHubStatus:^{
  155. [[JDFacade facade] dismissModalStack:YES completion:nil];
  156. }];
  157. }];
  158. } else if ([pushTypeCode isEqualToString:@"MEM_ALL_OUT"]) {//멤버 Any In 시
  159. NSString *path = API_GET_DEVICE_WARN_NODES;
  160. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  161. DeviceListModel *fdeviceList = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  162. modelClass:[DeviceListModel class] showLoadingView:NO];
  163. NSMutableString *onDevices, *openDevices;
  164. if (fdeviceList && fdeviceList.list && fdeviceList.list.count) {
  165. onDevices = [[NSMutableString alloc] init];
  166. openDevices = [[NSMutableString alloc] init];
  167. NSArray<DeviceModel> *devices = fdeviceList.list;
  168. for (DeviceModel *device in devices) {
  169. NSInteger typeId = [device.cmdclsTypeId integerValue];
  170. switch (typeId) {
  171. case 17001:
  172. case 17002:{//switch
  173. NSString *prefix = [onDevices isEmptyString] ? ksEmptyString : @", ";
  174. [onDevices appendFormat:@"%@%@", prefix, device.deviceName];
  175. }
  176. break;
  177. default: {//others
  178. NSString *prefix = [openDevices isEmptyString] ? ksEmptyString : @", ";
  179. [openDevices appendFormat:@"%@%@", prefix, device.deviceName];
  180. }
  181. break;
  182. }
  183. }
  184. if (![onDevices isEmptyString]) {
  185. [onDevices insertString:@"\n켜짐: " atIndex:0];
  186. }
  187. if (![openDevices isEmptyString]) {
  188. [openDevices insertString:@"\n열림: " atIndex:0];
  189. }
  190. }
  191. dispatch_async(dispatch_get_main_queue(), ^{
  192. NSString *tmpMessage = [NSString stringWithFormat:@"%@\n%@%@", message, onDevices ? onDevices : ksEmptyString, openDevices ? openDevices : ksEmptyString];
  193. [[JDFacade facade] confirmTitle:@"알림" message:tmpMessage btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  194. if (buttonIndex == 0) {
  195. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  196. }
  197. }];
  198. });
  199. });
  200. } else if ([pushTypeCode isEqualToString:@"MEM_ANY_IN"]) {//멤버 All Out 시, 멤버 Any In 시
  201. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  202. if (buttonIndex == 0) {
  203. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  204. }
  205. }];
  206. }
  207. }
  208. #pragma mark - Application Events
  209. - (void)applicationWillResignActive:(UIApplication *)application {
  210. // 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.
  211. // 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.
  212. }
  213. - (void)applicationDidEnterBackground:(UIApplication *)application {
  214. // 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.
  215. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  216. }
  217. - (void)applicationWillEnterForeground:(UIApplication *)application {
  218. // 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.
  219. application.applicationIconBadgeNumber = 0;
  220. }
  221. - (void)applicationDidBecomeActive:(UIApplication *)application {
  222. // 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.
  223. application.applicationIconBadgeNumber = 0;
  224. NSLog(@"%s\n %zd : 0=active, 1=inactive, 2=background", __PRETTY_FUNCTION__, [UIApplication sharedApplication].applicationState);
  225. if ([JDFacade facade].loginUser) {//현재 로그인 되있는 경우,
  226. //초대 내역 갱신.
  227. NSInteger invitationsCount = [[JDFacade facade].loginUser.invitationsCount integerValue];
  228. [[JDFacade facade] updateLoginInfo:^{//로그인 정보 갱신,
  229. if ([[JDFacade facade].loginUser.invitationsCount integerValue] > invitationsCount) {
  230. [[JDFacade facade] loadInvitationView];
  231. } else {
  232. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  233. }
  234. }];
  235. }
  236. }
  237. - (void)applicationWillTerminate:(UIApplication *)application {
  238. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  239. }
  240. @end