AppDelegate.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 fromFinishLaunching:YES];
  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. NSLog(@"didReceiveRemoteNotification");
  100. [self handlePushNotification:userInfo fromFinishLaunching:NO];
  101. }
  102. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  103. [application registerForRemoteNotifications];
  104. }
  105. - (void)handlePushNotification:(NSDictionary *)pushInfo
  106. fromFinishLaunching:(BOOL)fromFinishLaunching {
  107. NSLog(@"pushInfo %@", pushInfo);
  108. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  109. NSString *message = nil;
  110. NSString *title = nil;
  111. NSString *pushTypeCode = [pushInfo objectForKey:@"push_noti_type_code"];
  112. if (pushTypeCode) {
  113. message = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
  114. title = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"title"];
  115. NSString *homegrpId = [pushInfo objectForKey:@"homegrp_id"];
  116. [self handleWithPushTypeCode:pushTypeCode
  117. dummyCode:homegrpId
  118. message:message
  119. title:title
  120. fromFinishLaunching:fromFinishLaunching];
  121. return;
  122. }
  123. else {
  124. message = [[pushInfo objectForKey:@"aps"] objectForKey:@"alert"];
  125. }
  126. if (message && [message isKindOfClass:NSString.class] && [message isEmptyString]) {
  127. [[JDFacade facade] alert:message];
  128. }
  129. }
  130. - (void)handleWithPushTypeCode:(NSString *)pushTypeCode
  131. dummyCode:(NSString *)dummyCode
  132. message:(NSString *)message
  133. title:(NSString*)title
  134. fromFinishLaunching:(BOOL)fromFinishLaunching {
  135. NSLog(@"%s\n %@, %@, %@", __PRETTY_FUNCTION__, pushTypeCode, dummyCode, message);
  136. if ([pushTypeCode isEqualToString:@"HOME_MEM_INV"]) {//홈 초대받음
  137. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  138. if (buttonIndex == 0) {
  139. [[JDFacade facade] loadInvitationView];
  140. }
  141. }];
  142. } else if ([pushTypeCode isEqualToString:@"HOME_MEM_REF"]) {//홈초대 거절 시
  143. [[JDFacade facade] alert:message];
  144. [[JDFacade facade] updateMainViewController];
  145. }
  146. // else if ([pushTypeCode isEqualToString:@"HOME_MEM_BAN"]) {//홈에서 강퇴됨
  147. // [[JDFacade facade] alert:message completionHander:^{
  148. // [[JDFacade facade] updateMainViewController];
  149. // [[JDFacade facade] requestPollingHomeHubStatus:nil];
  150. // }];
  151. //
  152. // }
  153. else if ([pushTypeCode isEqualToString:@"HOME_MEM_SEL"]) {//홈에서 멤버가 탈퇴함
  154. [[JDFacade facade] alert:message];
  155. [[JDFacade facade] updateMainViewController];
  156. } else if ([pushTypeCode isEqualToString:@"HOME_DEL"]) {//홈그룹 삭제
  157. [[JDFacade facade] alert:message completionHander:^{
  158. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  159. }];
  160. } else if ([pushTypeCode isEqualToString:@"DVC_CER_REV"]) {//단말 인증 해지됨
  161. [[JDFacade facade] alert:message completionHander:^{
  162. [[JDFacade facade] logout];
  163. }];
  164. } else if ([pushTypeCode isEqualToString:@"MODE_CHG"] || [pushTypeCode isEqualToString:@"MODE_CHG_ERR"]) {//홈 모드 변경 시, 홈 모드 변경 시 일부장치 제어 실패
  165. [[JDFacade facade] alert:message];
  166. } else if ([pushTypeCode isEqualToString:@"RULE_EXC"] || [pushTypeCode isEqualToString:@"RULE_ERR"]) {//규칙 실행 시, 규칙 실패 누적으로 규칙
  167. [[JDFacade facade] alert:message];
  168. } else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"DVC_OWN_CHG"]) {//홈허브 삭제됨, 장치 소유주 변경 알림 - 대시보드
  169. [[JDFacade facade] alert:message completionHander:^{
  170. [[JDFacade facade] requestPollingHomeHubStatus:^{
  171. [[JDFacade facade] dismissModalStack:YES completion:nil];
  172. }];
  173. }];
  174. } else if ([pushTypeCode isEqualToString:@"MEM_ALL_OUT"]) {//멤버 Any In 시
  175. NSString *path = API_GET_DEVICE_WARN_NODES;
  176. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  177. DeviceListModel *fdeviceList = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  178. modelClass:[DeviceListModel class] showLoadingView:NO];
  179. NSMutableString *onDevices, *openDevices;
  180. if (fdeviceList && fdeviceList.list && fdeviceList.list.count) {
  181. onDevices = [[NSMutableString alloc] init];
  182. openDevices = [[NSMutableString alloc] init];
  183. NSArray<DeviceModel> *devices = fdeviceList.list;
  184. for (DeviceModel *device in devices) {
  185. NSInteger typeId = [device.cmdclsTypeId integerValue];
  186. switch (typeId) {
  187. case 17001:
  188. case 17002:{//switch
  189. NSString *prefix = [onDevices isEmptyString] ? ksEmptyString : @", ";
  190. [onDevices appendFormat:@"%@%@", prefix, device.deviceName];
  191. }
  192. break;
  193. default: {//others
  194. NSString *prefix = [openDevices isEmptyString] ? ksEmptyString : @", ";
  195. [openDevices appendFormat:@"%@%@", prefix, device.deviceName];
  196. }
  197. break;
  198. }
  199. }
  200. if (![onDevices isEmptyString]) {
  201. [onDevices insertString:@"\n켜짐: " atIndex:0];
  202. }
  203. if (![openDevices isEmptyString]) {
  204. [openDevices insertString:@"\n열림: " atIndex:0];
  205. }
  206. }
  207. dispatch_async(dispatch_get_main_queue(), ^{
  208. NSString *tmpMessage = [NSString stringWithFormat:@"%@\n%@%@", message, onDevices ? onDevices : ksEmptyString, openDevices ? openDevices : ksEmptyString];
  209. [[JDFacade facade] confirmTitle:@"알림" message:tmpMessage btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  210. if (buttonIndex == 0) {
  211. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  212. }
  213. }];
  214. });
  215. });
  216. } else if ([pushTypeCode isEqualToString:@"MEM_ANY_IN"]) {//멤버 All Out 시, 멤버 Any In 시
  217. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  218. if (buttonIndex == 0) {
  219. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  220. }
  221. }];
  222. }
  223. //권한양도 받은 경우
  224. else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD") ) {
  225. [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
  226. object:message];
  227. }
  228. //보낸 마스터 양도 거절
  229. else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD_REJECT") ) {
  230. [[JDFacade facade] alertTitle:title message:message];
  231. }
  232. //보낸 마스터 양도 완료 || 멤버가 계정 삭제함
  233. else if ( !fromFinishLaunching &&
  234. (EQUALS(pushTypeCode, @"MAS_GRD_ACCEPT")||EQUALS(pushTypeCode, @"HOME_MEM_SEL")) ) {
  235. [[JDFacade facade] alertTitle:title message:message completionHander:^{
  236. [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
  237. object:nil];
  238. }];
  239. }
  240. //계정 삭제 당함
  241. else if ( EQUALS(pushTypeCode, @"HOME_MEM_BAN") ) {
  242. [[JDFacade facade] alertTitle:title message:message completionHander:^{
  243. [[JDFacade facade]logout];
  244. }];
  245. }
  246. //
  247. }
  248. #pragma mark - Application Events
  249. - (void)applicationWillResignActive:(UIApplication *)application {
  250. // 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.
  251. // 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.
  252. }
  253. - (void)applicationDidEnterBackground:(UIApplication *)application {
  254. // 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.
  255. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  256. }
  257. - (void)applicationWillEnterForeground:(UIApplication *)application {
  258. // 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.
  259. application.applicationIconBadgeNumber = 0;
  260. }
  261. - (void)applicationDidBecomeActive:(UIApplication *)application {
  262. // 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.
  263. application.applicationIconBadgeNumber = 0;
  264. NSLog(@"%s\n %zd : 0=active, 1=inactive, 2=background", __PRETTY_FUNCTION__, [UIApplication sharedApplication].applicationState);
  265. if ([JDFacade facade].loginUser) {//현재 로그인 되있는 경우,
  266. //초대 내역 갱신.
  267. NSInteger invitationsCount = [[JDFacade facade].loginUser.invitationsCount integerValue];
  268. [[JDFacade facade] updateLoginInfo:^{//로그인 정보 갱신,
  269. if ([[JDFacade facade].loginUser.invitationsCount integerValue] > invitationsCount) {
  270. [[JDFacade facade] loadInvitationView];
  271. } else {
  272. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  273. }
  274. }];
  275. }
  276. }
  277. - (void)applicationWillTerminate:(UIApplication *)application {
  278. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  279. }
  280. @end