AppDelegate.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. [application cancelAllLocalNotifications];
  39. [self initializeApp];
  40. [self initRemoteNotification:launchOptions];
  41. return YES;
  42. }
  43. #pragma mark Handlers
  44. - (void)initializeApp {
  45. [Fabric with:@[[Crashlytics class]]];
  46. //set logger
  47. // [DDLog addLogger:[DDASLLogger sharedInstance]];
  48. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  49. [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
  50. }
  51. #pragma mark - Initialize Application
  52. - (void)checkLaunchOptions:(id)launchOptions {
  53. if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]) {
  54. NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]);
  55. [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
  56. }
  57. if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
  58. NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]);
  59. [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsLocalNotificationKey"];
  60. }
  61. }
  62. #pragma mark - APNS Setting
  63. /**
  64. APNS 초기화
  65. */
  66. - (void)initRemoteNotification:(NSDictionary *)launchOptions {
  67. // APNS에 디바이스를 등록한다.
  68. #if TARGET_IPHONE_SIMULATOR
  69. [JDFacade facade].APNSToken = @"IPHONE SIMULATOR";
  70. #else
  71. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  72. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  73. [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
  74. #endif
  75. if (launchOptions) {
  76. NSDictionary *pushInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  77. if (pushInfo) {
  78. [self handlePushNotification:pushInfo fromFinishLaunching:YES];
  79. }
  80. }
  81. }
  82. // 디바이스 토큰 받는곳
  83. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  84. NSMutableString *deviceId = [NSMutableString string];
  85. const unsigned char *ptr = (const unsigned char*) [deviceToken bytes];
  86. for(int i = 0 ; i < 32 ; i++) {
  87. [deviceId appendFormat:@"%02x", ptr[i]];
  88. }
  89. //메모리에 저장.
  90. [JDFacade facade].APNSToken = deviceId;
  91. NSLog(@"APNS Device Token: %@", deviceId);
  92. }
  93. // 서버에 등록 실패했을 경우.
  94. - (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  95. {
  96. NSLog(@"didFailToRegisterForRemoteNotifications: %@", error);
  97. }
  98. // 푸시 처리
  99. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
  100. NSLog(@"didReceiveRemoteNotification");
  101. [self handlePushNotification:userInfo fromFinishLaunching:NO];
  102. }
  103. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  104. [application registerForRemoteNotifications];
  105. }
  106. - (void)handlePushNotification:(NSDictionary *)pushInfo
  107. fromFinishLaunching:(BOOL)fromFinishLaunching {
  108. NSLog(@"pushInfo %@", pushInfo);
  109. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  110. [[UIApplication sharedApplication] cancelAllLocalNotifications];
  111. NSString *message = nil;
  112. NSString *title = nil;
  113. NSString *pushTypeCode = [pushInfo objectForKey:@"push_noti_type_code"];
  114. if (pushTypeCode) {
  115. message = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
  116. title = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"title"];
  117. NSString *homegrpId = [pushInfo objectForKey:@"homegrp_id"];
  118. [self handleWithPushTypeCode:pushTypeCode
  119. dummyCode:homegrpId
  120. message:message
  121. title:title
  122. fromFinishLaunching:fromFinishLaunching];
  123. return;
  124. }
  125. else {
  126. message = [[pushInfo objectForKey:@"aps"] objectForKey:@"alert"];
  127. }
  128. if (message && [message isKindOfClass:NSString.class] && [message isEmptyString]) {
  129. [[JDFacade facade] alert:message];
  130. }
  131. }
  132. - (void)handleWithPushTypeCode:(NSString *)pushTypeCode
  133. dummyCode:(NSString *)dummyCode
  134. message:(NSString *)message
  135. title:(NSString*)title
  136. fromFinishLaunching:(BOOL)fromFinishLaunching {
  137. NSLog(@"%s\n %@, %@, %@", __PRETTY_FUNCTION__, pushTypeCode, dummyCode, message);
  138. if ([pushTypeCode isEqualToString:@"HOME_MEM_INV"]) {//홈 초대받음
  139. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  140. if (buttonIndex == 0) {
  141. [[JDFacade facade] loadInvitationView];
  142. }
  143. }];
  144. } else if ([pushTypeCode isEqualToString:@"HOME_MEM_REF"]) {//홈초대 거절 시
  145. [[JDFacade facade] alert:message];
  146. [[JDFacade facade] updateMainViewController];
  147. }
  148. // else if ([pushTypeCode isEqualToString:@"HOME_MEM_BAN"]) {//홈에서 강퇴됨
  149. // [[JDFacade facade] alert:message completionHander:^{
  150. // [[JDFacade facade] updateMainViewController];
  151. // [[JDFacade facade] requestPollingHomeHubStatus:nil];
  152. // }];
  153. //
  154. // }
  155. else if ([pushTypeCode isEqualToString:@"HOME_MEM_SEL"]) {//홈에서 멤버가 탈퇴함
  156. [[JDFacade facade] alert:message];
  157. [[JDFacade facade] updateMainViewController];
  158. } else if ([pushTypeCode isEqualToString:@"HOME_DEL"]) {//홈그룹 삭제
  159. [[JDFacade facade] alert:message completionHander:^{
  160. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  161. }];
  162. } else if ([pushTypeCode isEqualToString:@"DVC_CER_REV"]) {//단말 인증 해지됨
  163. [[JDFacade facade] alert:message completionHander:^{
  164. [[JDFacade facade] logout];
  165. }];
  166. } else if ([pushTypeCode isEqualToString:@"MODE_CHG"] || [pushTypeCode isEqualToString:@"MODE_CHG_ERR"]) {//홈 모드 변경 시, 홈 모드 변경 시 일부장치 제어 실패
  167. [[JDFacade facade] alert:message];
  168. } else if ([pushTypeCode isEqualToString:@"RULE_EXC"] || [pushTypeCode isEqualToString:@"RULE_ERR"]) {//규칙 실행 시, 규칙 실패 누적으로 규칙
  169. [[JDFacade facade] alert:message];
  170. } else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"DVC_OWN_CHG"]) {//홈허브 삭제됨, 장치 소유주 변경 알림 - 대시보드
  171. [[JDFacade facade] alert:message completionHander:^{
  172. [[JDFacade facade] requestPollingHomeHubStatus:^{
  173. [[JDFacade facade] dismissModalStack:YES completion:nil];
  174. }];
  175. }];
  176. } else if ([pushTypeCode isEqualToString:@"MEM_ALL_OUT"]) {//멤버 Any In 시
  177. NSString *path = API_GET_DEVICE_WARN_NODES;
  178. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  179. DeviceListModel *fdeviceList = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  180. modelClass:[DeviceListModel class] showLoadingView:NO];
  181. NSMutableString *onDevices, *openDevices;
  182. if (fdeviceList && fdeviceList.list && fdeviceList.list.count) {
  183. onDevices = [[NSMutableString alloc] init];
  184. openDevices = [[NSMutableString alloc] init];
  185. NSArray<DeviceModel> *devices = fdeviceList.list;
  186. for (DeviceModel *device in devices) {
  187. NSInteger typeId = [device.cmdclsTypeId integerValue];
  188. switch (typeId) {
  189. case 17001:
  190. case 17002:{//switch
  191. NSString *prefix = [onDevices isEmptyString] ? ksEmptyString : @", ";
  192. [onDevices appendFormat:@"%@%@", prefix, device.deviceName];
  193. }
  194. break;
  195. default: {//others
  196. NSString *prefix = [openDevices isEmptyString] ? ksEmptyString : @", ";
  197. [openDevices appendFormat:@"%@%@", prefix, device.deviceName];
  198. }
  199. break;
  200. }
  201. }
  202. if (![onDevices isEmptyString]) {
  203. [onDevices insertString:@"\n켜짐: " atIndex:0];
  204. }
  205. if (![openDevices isEmptyString]) {
  206. [openDevices insertString:@"\n열림: " atIndex:0];
  207. }
  208. }
  209. dispatch_async(dispatch_get_main_queue(), ^{
  210. NSString *tmpMessage = [NSString stringWithFormat:@"%@\n%@%@", message, onDevices ? onDevices : ksEmptyString, openDevices ? openDevices : ksEmptyString];
  211. [[JDFacade facade] confirmTitle:@"알림" message:tmpMessage btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  212. if (buttonIndex == 0) {
  213. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  214. }
  215. }];
  216. });
  217. });
  218. } else if ([pushTypeCode isEqualToString:@"MEM_ANY_IN"]) {//멤버 All Out 시, 멤버 Any In 시
  219. [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  220. if (buttonIndex == 0) {
  221. [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
  222. }
  223. }];
  224. }
  225. //권한양도 받은 경우
  226. else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD") ) {
  227. [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
  228. object:message];
  229. }
  230. //보낸 마스터 양도 거절
  231. else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD_REJECT") ) {
  232. [[JDFacade facade] alertTitle:title message:message];
  233. }
  234. //보낸 마스터 양도 완료 || 멤버가 계정 삭제함
  235. else if ( !fromFinishLaunching &&
  236. (EQUALS(pushTypeCode, @"MAS_GRD_ACCEPT")||EQUALS(pushTypeCode, @"HOME_MEM_SEL")) ) {
  237. [[JDFacade facade] alertTitle:title message:message completionHander:^{
  238. [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
  239. object:nil];
  240. }];
  241. }
  242. //계정 삭제 당함
  243. else if ( EQUALS(pushTypeCode, @"HOME_MEM_BAN") ) {
  244. [[JDFacade facade] alertTitle:title message:message completionHander:^{
  245. [[JDFacade facade]logout];
  246. }];
  247. }
  248. //타 사용자가 내 번호로 인증받음
  249. else if ( EQUALS(pushTypeCode, @"MOBILE_NUM_CHG") ) {
  250. [[JDFacade facade] confirmTitle:@"휴대폰 번호 변경"
  251. message:message
  252. btnOKLabel:@"보기"
  253. btnCancelLabel:@"닫기"
  254. completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  255. if (buttonIndex == 0) {
  256. [[JDFacade facade] loadSettingsNumChangeView];
  257. }
  258. }];
  259. }
  260. //홈허브 오프라인
  261. else if ( EQUALS(pushTypeCode, @"HOMEHUB_OFF") ) {
  262. [[JDFacade facade] confirmTitle:@"홈허브 오프라인"
  263. message:message
  264. btnOKLabel:@"보기"
  265. btnCancelLabel:@"닫기"
  266. completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  267. if (buttonIndex == 0) {
  268. [[JDFacade facade] loadHomeHubView];
  269. }
  270. }];
  271. }
  272. //
  273. else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"MODE_CHG"]) {//홈허브 삭제, 홈모드 변경 알림
  274. [[JDFacade facade] alert:message];
  275. }
  276. }
  277. #pragma mark - Application Events
  278. - (void)applicationWillResignActive:(UIApplication *)application {
  279. // 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.
  280. // 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.
  281. }
  282. - (void)applicationDidEnterBackground:(UIApplication *)application {
  283. // 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.
  284. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  285. }
  286. - (void)applicationWillEnterForeground:(UIApplication *)application {
  287. // 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.
  288. application.applicationIconBadgeNumber = 0;
  289. }
  290. - (void)applicationDidBecomeActive:(UIApplication *)application {
  291. // 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.
  292. application.applicationIconBadgeNumber = 0;
  293. NSLog(@"%s\n %zd : 0=active, 1=inactive, 2=background", __PRETTY_FUNCTION__, [UIApplication sharedApplication].applicationState);
  294. if ([JDFacade facade].loginUser) {//현재 로그인 되있는 경우,
  295. //초대 내역 갱신.
  296. NSInteger invitationsCount = [[JDFacade facade].loginUser.invitationsCount integerValue];
  297. [[JDFacade facade] updateLoginInfo:^{//로그인 정보 갱신,
  298. if ([[JDFacade facade].loginUser.invitationsCount integerValue] > invitationsCount) {
  299. [[JDFacade facade] loadInvitationView];
  300. } else {
  301. [[JDFacade facade] requestPollingHomeHubStatus:nil];
  302. }
  303. }];
  304. }
  305. }
  306. - (void)applicationWillTerminate:(UIApplication *)application {
  307. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  308. }
  309. @end