JDFacade.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. //
  2. // JDFacade.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 ObjectiveC.runtime;
  9. #import "JDFacade.h"
  10. #import "JDUserDefaults.h"
  11. #import "CypherUtil.h"
  12. #import "JDUUID.h"
  13. #import "CustomLoadingView.h"
  14. #import "CustomImageView.h"
  15. #import "RequestHandler.h"
  16. //OpenSource
  17. #ifndef PRODUCT_MODE
  18. #import "FLEXManager.h"
  19. #endif
  20. #import "UIView+Toast.h"
  21. #import "JDProgressHUD.h"
  22. #import "Valet.h"
  23. #import "VALValet.h"
  24. #import "LoginViewController.h"
  25. #import "MainViewController.h"
  26. #import "DeviceModel.h"
  27. #import "HomeHubViewController.h"
  28. @interface JDFacade () {
  29. VALValet *_valet;
  30. JDProgressHUD *_HUD;
  31. NSTimer *_homehubBackgroundTimer;
  32. }
  33. @end
  34. @implementation JDFacade
  35. @synthesize tmpEmailId = _tmpEmailId;
  36. #pragma mark - Properties
  37. - (NSString *)deviceUUID {
  38. if (!_deviceUUID) {
  39. _deviceUUID = [[JDUUID UUIDHandler] getUUID];
  40. }
  41. return _deviceUUID;
  42. }
  43. - (NSString *)APNSToken {
  44. return _APNSToken ? _APNSToken : ksEmptyString;
  45. }
  46. - (NSString *)tmpEmailId {
  47. NSString *enTmpEmailId = [self objectForKeyFromUserDefaults:USDEF_APP_TMP_EMAIL];
  48. _tmpEmailId = [CypherUtil AES128Decrypt:enTmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  49. return _tmpEmailId ? _tmpEmailId : ksEmptyString;
  50. }
  51. - (void)setTmpEmailId:(NSString *)tmpEmailId {
  52. NSString *enTmpEmailId = [CypherUtil AES128Encrypt:tmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  53. [self storeObjectToUserDefaults:enTmpEmailId forKey:USDEF_APP_TMP_EMAIL];
  54. }
  55. - (void)setCurrentOperation:(NSOperation *)currentOperation {
  56. [CustomLoadingView loadingView].operation = currentOperation;
  57. }
  58. - (NSString *)deviceHostName {
  59. return [self hostnameOfDevice];
  60. }
  61. - (void)setLoginUser:(LoginModel *)loginUser {
  62. _loginUser = loginUser;
  63. if (!_loginUser) {
  64. if (_homehubBackgroundTimer) {
  65. [_homehubBackgroundTimer invalidate];
  66. _homehubBackgroundTimer = nil;
  67. }
  68. }
  69. }
  70. - (NSString *)hostnameOfDevice {
  71. char baseHostName[256];
  72. int success = gethostname(baseHostName, 255);
  73. if (success != 0) return nil;
  74. baseHostName[255] = '\0';
  75. #if !TARGET_IPHONE_SIMULATOR
  76. NSLog(@"%s\n %@, %s", __PRETTY_FUNCTION__, @"!TARGET_IPHONE_SIMULATOR", baseHostName);
  77. NSString *hostname = [NSString stringWithFormat:@"%s", baseHostName];
  78. if (![hostname hasSuffix:@"local"]) {
  79. hostname = [NSString stringWithFormat:@"%s.local", baseHostName];
  80. }
  81. return hostname;
  82. #else
  83. return [NSString stringWithFormat:@"%s", baseHostName];
  84. #endif
  85. }
  86. #pragma mark - View Facade
  87. - (AppDelegate *)appDelegate {
  88. return (AppDelegate *)[UIApplication sharedApplication].delegate;
  89. }
  90. #pragma mark - 화면 제어
  91. - (UIViewController *)currentViewController {
  92. id appDelegate = [UIApplication sharedApplication].delegate;
  93. UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
  94. if (vc.presentedViewController) {
  95. while (vc.presentedViewController) {
  96. vc = vc.presentedViewController;
  97. }
  98. if ([vc isKindOfClass:[UINavigationController class]]) {
  99. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  100. vc = [vcArray objectAtIndex:vcArray.count - 1];
  101. }
  102. return vc;
  103. }
  104. if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
  105. vc = vc.presentingViewController;
  106. }
  107. if ([vc isKindOfClass:[UINavigationController class]]) {
  108. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  109. vc = [vcArray objectAtIndex:vcArray.count - 1];
  110. }
  111. return vc;
  112. }
  113. - (id)viewControllerOnNaviationController:(Class)viewControllerClass {
  114. UIViewController *targetVc = nil;
  115. UINavigationController *navigationController = self.currentViewController.navigationController;
  116. if (!navigationController) {
  117. navigationController = (UINavigationController *)self.currentViewController.presentingViewController;
  118. }
  119. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  120. for (UIViewController *vc in navigationController.viewControllers) {
  121. if ([vc isKindOfClass:viewControllerClass]) {
  122. targetVc = vc;
  123. break;
  124. }
  125. }
  126. }
  127. return targetVc;
  128. }
  129. - (id)viewControllerOnPresentingViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass {
  130. return [self viewControllerOnPresentingViewController:pvc viewControllerClass:viewControllerClass tryTimes:10];
  131. }
  132. - (id)viewControllerOnPresentingViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass tryTimes:(NSInteger)tryTimes {
  133. UIViewController *vc = pvc.presentingViewController;
  134. if (![vc isKindOfClass:viewControllerClass] && tryTimes > 0) {
  135. vc = [self viewControllerOnPresentingViewController:vc viewControllerClass:viewControllerClass tryTimes:tryTimes-1];
  136. }
  137. return vc;
  138. }
  139. - (id)viewControllerOnPresentedViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass {
  140. return [self viewControllerOnPresentedViewController:pvc viewControllerClass:viewControllerClass tryTimes:10];
  141. }
  142. - (id)viewControllerOnPresentedViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass tryTimes:(NSInteger)tryTimes {
  143. UIViewController *vc = pvc.presentedViewController;
  144. if (![vc isKindOfClass:viewControllerClass] && tryTimes > 0) {
  145. vc = [self viewControllerOnPresentedViewController:vc viewControllerClass:viewControllerClass tryTimes:tryTimes-1];
  146. }
  147. return vc;
  148. }
  149. #pragma mark - KeychainItem Wrapper
  150. static NSString *const ksKeychainIdentifier = @"OneCableACCOUNT";
  151. static NSString *const ksKeychainArchiveData = @"_archiveData";
  152. - (void)storeObjectToKeychain:(id)object forKey:(NSString *)aKey {
  153. if (!_valet) {
  154. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  155. }
  156. NSMutableDictionary *dict = nil;
  157. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  158. if (archiveData) {
  159. dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  160. }
  161. if (!dict) {
  162. dict = [[NSMutableDictionary alloc] init];
  163. }
  164. [dict setObject:object forKey:aKey];
  165. archiveData = [NSKeyedArchiver archivedDataWithRootObject:dict];
  166. [_valet setObject:archiveData forKey:ksKeychainArchiveData];
  167. }
  168. - (id)objectForKeyFromKeychain:(NSString *)aKey {
  169. if (!_valet) {
  170. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  171. }
  172. NSMutableDictionary *dict = nil;
  173. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  174. id obj = nil;
  175. if (archiveData) {
  176. dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  177. obj = [dict objectForKey:aKey];
  178. }
  179. return obj;
  180. }
  181. - (void)removeObjectAtKeychain:(NSString *)aKey {
  182. if (!_valet) {
  183. _valet = [[VALValet alloc] initWithIdentifier:ksKeychainIdentifier accessibility:VALAccessibilityWhenUnlockedThisDeviceOnly];
  184. }
  185. NSMutableDictionary *dict = nil;
  186. NSData *archiveData = [_valet objectForKey:ksKeychainArchiveData];
  187. if (archiveData) {
  188. dict = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
  189. [dict removeObjectForKey:aKey];
  190. }
  191. archiveData = [NSKeyedArchiver archivedDataWithRootObject:dict];
  192. [_valet setObject:archiveData forKey:ksKeychainArchiveData];
  193. }
  194. #pragma mark - UserDefautls - Local Store
  195. - (void)storeObjectToUserDefaults:(id)object forKey:(NSString *)aKey {
  196. [[JDUserDefaults defaults] syncronizeObject:object forKey:aKey];
  197. }
  198. - (id)objectForKeyFromUserDefaults:(NSString *)aKey {
  199. return [[JDUserDefaults defaults] objectForKey:aKey];
  200. }
  201. #pragma mark - Alert & Loading
  202. - (void)loadIndicator:(BOOL)showIndicator allowUserInteraction:(BOOL)allowUserInteracton {
  203. //로딩시 터치 방지
  204. if(showIndicator) {
  205. dispatch_async(dispatch_get_main_queue(), ^{
  206. [[JDFacade facade].currentViewController.view endEditing:YES];
  207. UIView *topView = [CommonUtil topView];
  208. [[CustomLoadingView loadingView] showInView:topView];
  209. });
  210. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  211. } else {
  212. dispatch_async(dispatch_get_main_queue(), ^{
  213. [[CustomLoadingView loadingView] hide];
  214. });
  215. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  216. }
  217. }
  218. - (void)showLoadingWhileExecutingBlock:(dispatch_block_t)block completionHandler:(JDFacadeCompletionCallBackHandler)completion {
  219. [[CustomLoadingView loadingView] showInView:[CommonUtil topView] whileExecutingBlock:block completionHandler:completion];
  220. }
  221. #pragma mark - Alert UI
  222. - (void)alert:(NSString *)message {
  223. [self alertTitle:@"알림" message:message];
  224. }
  225. - (void)alertTitle:(NSString *)title message:(NSString *)message {
  226. [self.currentViewController.view endEditing:YES];
  227. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  228. [alert show];
  229. }
  230. - (void)alert:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)completion {
  231. [self alertTitle:@"알림" message:message completionHander:completion];
  232. }
  233. - (void)alertTitle:(NSString *)title message:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)completion {
  234. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  235. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  236. if (completion) {
  237. completion();
  238. }
  239. }];
  240. }
  241. - (void)confirm:(NSString *)message completion:(CustomAlertViewCallBackHandler)completion {
  242. [self confirmTitle:@"알림" message:message completion:completion];
  243. }
  244. - (void)confirmTitle:(NSString *)title message:(NSString *)message completion:(CustomAlertViewCallBackHandler)completion {
  245. [self confirmTitle:title message:message btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:completion];
  246. }
  247. - (void)confirmTitle:(NSString *)title message:(NSString *)message btnOKLabel:(NSString *)btnOKLabel btnCancelLabel:(NSString *)btnCancelLabel completion:(CustomAlertViewCallBackHandler)completion {
  248. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:title message:message delegate:nil OKButtonTitle:btnOKLabel cancelButtonTitle:btnCancelLabel];
  249. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  250. if (completion) {
  251. completion(alertView, buttonIndex);
  252. }
  253. }];
  254. }
  255. - (void)retryAlert:(NSString *)message target:(id)target selector:(SEL)selector {
  256. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  257. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  258. if (buttonIndex == 1) {
  259. if ([target respondsToSelector:selector]) {
  260. [target performSelector:selector withObject:nil afterDelay:0.0f];
  261. }
  262. }
  263. }];
  264. }
  265. - (void)retryAlert:(NSString *)message target:(id)target selector:(SEL)selector arguments:(id)arguments,... {
  266. va_list args;
  267. va_start(args, arguments);
  268. NSInteger i = 0;
  269. NSMutableArray *argsArray = [[NSMutableArray alloc] init];
  270. [argsArray addObject:arguments];
  271. while ((arguments = va_arg(args, id)) != nil) {//루프 - 입력된 메시지를 받아옴.
  272. [argsArray addObject:arguments];
  273. i++;
  274. }
  275. va_end(args);
  276. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  277. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  278. if (buttonIndex == 0) {
  279. if (target && selector) {
  280. NSMethodSignature *sig = [target methodSignatureForSelector:selector];
  281. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
  282. NSInteger index = 2;
  283. [invocation setTarget:target]; // index 0 (hidden)
  284. [invocation setSelector:selector]; //index 1 (hidden)
  285. for (id argument in argsArray) {
  286. [invocation setArgument:(void *)&argument atIndex:index++];
  287. }
  288. [invocation invoke];
  289. }
  290. }
  291. }];
  292. }
  293. - (void)retryAlert:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)handler {
  294. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  295. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  296. if (buttonIndex == 1) {//재시도
  297. if (handler) {
  298. handler();
  299. }
  300. }
  301. }];
  302. }
  303. #pragma mark - ActionSeet UI
  304. // TODO : Action Sheet 출력 메소드 만들것
  305. -(void)selectDatas:(id)target listInfo:(DataSelectListModel *)listInfo completion:(JDFacadeSelectCallBackHandler)completion{
  306. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:listInfo.title
  307. message:nil
  308. preferredStyle:UIAlertControllerStyleActionSheet];
  309. for (DataSelectModel *info in listInfo.list) {
  310. UIAlertAction *action = [UIAlertAction actionWithTitle:info.title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  311. if (completion) {
  312. completion(info);
  313. }
  314. }];
  315. if ([info getColorCode] != nil) {
  316. [action setValue:[info getColorCode] forKey:@"titleTextColor"];
  317. }
  318. // [action setValue:[UIColor redColor] forKey:@"titleTextColor"];
  319. [alertController addAction:action];
  320. }
  321. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"취소" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  322. }];
  323. [alertController addAction:cancelAction];
  324. // NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:alertController.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:IPHONE_HEIGHT*.5f];
  325. // [alertController.view addConstraint:constraint];
  326. [alertController.view mas_makeConstraints:^(MASConstraintMaker *make) {
  327. make.height.lessThanOrEqualTo(@(IPHONE_HEIGHT*.5f));
  328. }];
  329. [target presentViewController:alertController animated:YES completion:nil];
  330. }
  331. - (void)fireLocalNotification:(NSString *)message {
  332. NSLog(@"fireLocalNotification %@", message);
  333. NSDate *now = [NSDate date];
  334. UILocalNotification *localNotif = [[UILocalNotification alloc] init];
  335. localNotif.fireDate = now;
  336. NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
  337. localNotif.timeZone = timezone;
  338. localNotif.hasAction = YES;
  339. localNotif.alertBody = message;
  340. localNotif.alertAction = @"View";
  341. localNotif.soundName = UILocalNotificationDefaultSoundName;
  342. localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
  343. [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
  344. }
  345. - (void)toast:(NSString *)message {
  346. [[CommonUtil topView] makeToast:message];
  347. }
  348. #pragma mark - CheckBox && Radiobutton Status
  349. - (id)getRadioButtonStatus:(id)object {
  350. if (!object)
  351. return @NO;
  352. return objc_getAssociatedObject(object, ksCustomRadioButtonStatus);
  353. }
  354. - (void)setRadioButtonStatus:(id)status object:(id)object {
  355. if (!object)
  356. return;
  357. objc_setAssociatedObject(object, ksCustomRadioButtonStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for radio box
  358. }
  359. - (id)getCheckBoxStatus:(id)object {
  360. if (!object)
  361. return @NO;
  362. return objc_getAssociatedObject(object, ksCustomCheckBoxStatus);
  363. }
  364. - (void)setCheckBoxStatus:(id)status object:(id)object {
  365. if (!object)
  366. return;
  367. objc_setAssociatedObject(object, ksCustomCheckBoxStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for check box
  368. }
  369. #pragma mark - 화면이동 제어
  370. - (void)dismissModalStack:(BOOL)animated completion:(JDFacadeCompletionCallBackHandler)completion {
  371. UIViewController *vc = self.currentViewController;
  372. while (vc.presentingViewController) {
  373. vc = vc.presentingViewController;
  374. }
  375. CATransition *transition = [CATransition animation];
  376. transition.duration = kfTransitionRightDur;
  377. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  378. transition.type = kCATransitionMoveIn;
  379. transition.subtype = kCATransitionFromBottom;
  380. [vc.view.window.layer addAnimation:transition forKey:nil];
  381. [vc dismissViewControllerAnimated:NO completion:^{
  382. if (completion) {
  383. completion();
  384. }
  385. }];
  386. }
  387. - (void)presentViewControllerByPush:(UIViewController *)vc {
  388. CATransition *transition = [CATransition animation];
  389. transition.duration = kfTransitionRightDur;
  390. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  391. transition.type = kCATransitionPush;
  392. transition.subtype = kCATransitionFromRight;
  393. [self.currentViewController.view.window.layer addAnimation:transition forKey:nil];
  394. [self.currentViewController presentViewController:vc animated:NO completion:nil];
  395. }
  396. - (void)presentViewControllerByPush:(UIViewController *)vc pvc:(UIViewController *)pvc {
  397. CATransition *transition = [CATransition animation];
  398. transition.duration = kfTransitionRightDur;
  399. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  400. transition.type = kCATransitionPush;
  401. transition.subtype = kCATransitionFromRight;
  402. [pvc.view.window.layer addAnimation:transition forKey:nil];
  403. [pvc presentViewController:vc animated:NO completion:nil];
  404. }
  405. - (UIViewController *)presentedViewController:(UIViewController *)vc {
  406. UIViewController *presentedViewController = vc.presentedViewController;
  407. if (presentedViewController) {
  408. return [self presentedViewController:presentedViewController];
  409. }
  410. return vc;
  411. }
  412. - (void)dismissViewControllerByPush:(UIViewController *)vc {
  413. CATransition *transition = [CATransition animation];
  414. transition.duration = kfTransitionRightDur;
  415. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  416. transition.type = kCATransitionPush;
  417. transition.subtype = kCATransitionFromBottom;
  418. UIViewController *presentedViewController = [self presentedViewController:vc];
  419. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  420. [vc dismissViewControllerAnimated:NO completion:nil];
  421. }
  422. - (void)dismissViewControllerByPush:(UIViewController *)vc completion:(JDFacadeCompletionCallBackHandler)completion {
  423. CATransition *transition = [CATransition animation];
  424. transition.duration = kfTransitionRightDur;
  425. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  426. transition.type = kCATransitionPush;
  427. transition.subtype = kCATransitionFromLeft;
  428. UIViewController *presentedViewController = [self presentedViewController:vc];
  429. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  430. [vc dismissViewControllerAnimated:NO completion:^{
  431. if (completion) {
  432. completion();
  433. }
  434. }];
  435. }
  436. - (void)dismissAllViewControllers {
  437. UIViewController *vc = self.currentViewController;
  438. if (vc.presentingViewController) {
  439. [vc dismissViewControllerAnimated:NO completion:^{
  440. [self dismissAllViewControllers];
  441. }];
  442. }
  443. }
  444. #pragma mark - Biz Logic
  445. - (void)requestPollingHomeHubStatusInBackground {
  446. //schedul timer.
  447. if (!_homehubBackgroundTimer) {
  448. [self requestPollingHomeHubStatus:^{
  449. _homehubBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestPollingHomeHubStatus) userInfo:nil repeats:YES];
  450. }];
  451. }
  452. }
  453. - (void)requestPollingHomeHubStatus {
  454. [self requestPollingHomeHubStatus:nil];
  455. }
  456. - (void)requestPollingHomeHubStatus:(JDFacadeCompletionCallBackHandler)completion {
  457. NSString *path = API_GET_DEVICE_HOMEHUB_STATUS;
  458. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  459. DeviceModel *homehub = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  460. modelClass:[DeviceModel class] showLoadingView:NO];
  461. if (homehub && homehub.onlineState && ![homehub.onlineState isEmptyString]) {
  462. [JDFacade facade].loginUser.homehubOnlineState = homehub.onlineState;
  463. [JDFacade facade].loginUser.homehubCreateDatetime = homehub.createDatetime;
  464. } else {
  465. [JDFacade facade].loginUser.homehubDeviceId = nil;
  466. [JDFacade facade].loginUser.homehubOnlineState = nil;
  467. [JDFacade facade].loginUser.homehubCreateDatetime = nil;
  468. }
  469. [_mainViewController updateHomeHubStatusToChildViewController];
  470. //update global - homehub state
  471. if ([[JDFacade facade].currentViewController isKindOfClass:[HomeHubViewController class]]) {
  472. HomeHubViewController *vc = (HomeHubViewController *)[JDFacade facade].currentViewController;
  473. [vc updateHomeHubStatus];
  474. }
  475. #ifdef DEBUG_MODE
  476. NSLogInfo(@"==########== homehub state = %@ ==########==", [JDFacade facade].loginUser.homehubOnlineState);
  477. #endif
  478. if (completion) {
  479. completion();
  480. }
  481. });
  482. }
  483. #pragma mark - UI Flow
  484. - (void)gotoLoginView {
  485. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  486. [[JDFacade facade].appDelegate.window setRootViewController:vc];
  487. }
  488. //- (void)gotoLoginViewWithExpiring {
  489. // LoginViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  490. // [vc actionAfterLogout];
  491. //}
  492. //
  493. - (void)logout {
  494. LoginViewController *lvc = (LoginViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  495. [lvc requestLogout];
  496. }
  497. - (void)loadInvitationView {
  498. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"InvitationListViewController" storyboardName:@"Main"];
  499. [self.currentViewController presentViewController:vc animated:YES completion:nil];
  500. }
  501. //- (void)checkDefaultHome {
  502. // if (!self.loginUser) {//로그인이 안된 경우, 불필요함.
  503. // return;
  504. // }
  505. //
  506. // [self updateHomegrpListForLoginUser:^{
  507. // //1. 다른 홈이 있는지 확인 - 정렬순서대로 기본홈을 설정 - currentHome
  508. // if (self.loginUser.homegrpList && self.loginUser.homegrpList.count) {
  509. // self.loginHomeGroup = self.loginUser.homegrpList[0];
  510. // [self gotoWishMenu:KNMenuIdDashboard];
  511. // return;
  512. // }
  513. //
  514. // //2. 다른 홈이 없는 경우, - 홈만들기로 이동함.
  515. // CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:NSLocalizedString(@"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?", @"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?") delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  516. // [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  517. // if (buttonIndex == 0) {//OK
  518. // [self gotoStartHome:NO];
  519. // } else {
  520. // [self logout];
  521. // }
  522. // }];
  523. // }];
  524. //}
  525. - (void)gotoStartHome:(BOOL)canGoBack {
  526. // StartHomeViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"StartHomeViewController" storyboardName:@"SignUp"];
  527. // vc.canGoBack = canGoBack;
  528. // [[JDFacade facade] presentViewControllerByPush:vc pvc:self.currentViewController];
  529. }
  530. - (void)gotoWishMenu:(KNMenuId)menuId {
  531. [self gotoWishMenu:menuId completion:nil];
  532. }
  533. - (void)gotoWishMenu:(KNMenuId)menuId completion:(JDFacadeCompletionCallBackHandler)completion {
  534. self.wishMenuId = menuId;
  535. switch (self.wishMenuId) {
  536. case KNMenuIdDashboard: {
  537. // [_mainViewController btnCollapseTouched:nil];
  538. [[JDFacade facade] requestPollingHomeHubStatus:^{
  539. [[JDFacade facade] dismissModalStack:YES completion:nil];
  540. }];
  541. }
  542. break;
  543. case KNMenuIdThings: {
  544. [[JDFacade facade] dismissModalStack:YES completion:^{
  545. [_mainViewController loadThingsViewController];
  546. }];
  547. }
  548. break;
  549. case KNMenuIdRules: {
  550. [[JDFacade facade] dismissModalStack:YES completion:^{
  551. [_mainViewController loadRulesViewController];
  552. }];
  553. }
  554. break;
  555. case KNMenuIdHomeMember: {
  556. [[JDFacade facade] dismissModalStack:YES completion:^{
  557. [_mainViewController loadMembersViewController];
  558. }];
  559. }
  560. break;
  561. case KNMenuIdManagement: {
  562. [[JDFacade facade] dismissModalStack:YES completion:^{
  563. [_mainViewController loadManagementViewController];
  564. }];
  565. }
  566. break;
  567. default:
  568. break;
  569. }
  570. }
  571. - (void)gotoHomeHubRegistration {
  572. // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubStartViewController" storyboardName:@"HomeHub"];
  573. //
  574. // vc.providesPresentationContextTransitionStyle = YES;
  575. // vc.definesPresentationContext = YES;
  576. //
  577. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  578. //
  579. // [self.currentViewController presentViewController:vc animated:NO completion:nil];
  580. }
  581. //- (void)updateHomegrpListForLoginUser:(JDFacadeCompletionCallBackHandler)completion {
  582. //
  583. // NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID};
  584. //
  585. // dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  586. // HomeGroupListModel *homegrpList = [[RequestHandler handler] sendSyncGetRequestAPIPath:API_GET_HOMEGROUP parameters:parameter
  587. // modelClass:[HomeGroupListModel class] showLoadingView:YES];
  588. //
  589. //
  590. // // NSLog(@"%s\n %@", __PRETTY_FUNCTION__, homegrpList);
  591. // //홈그룹을 설정함.
  592. // self.loginUser.homegrpList = homegrpList && homegrpList.homegrpList ? homegrpList.homegrpList : nil;
  593. //
  594. // //로그인 홈을 지정함.
  595. // for (HomeGroupModel *homegrp in self.loginUser.homegrpList) {
  596. // if ([self.loginUser.homegrpId isEqualToString:homegrp.homegrpId]) {
  597. // self.loginHomeGroup = homegrp;
  598. // break;
  599. // }
  600. // }
  601. //
  602. //// [[LocationHandler handler] resetAllMonitoredRegions]; //현재 앱이 구동 중이면, 위치 센서를 다시 등록해야함.
  603. //// [[LocationHandler handler] registerGeofencingForHomeGroupIndex:0]; //모든 홈 그룹을 다시 모니터링 등록 - 루프
  604. //
  605. // if (completion) {
  606. // completion();
  607. // }
  608. // });
  609. //}
  610. - (void)updateLoginInfo:(JDFacadeCompletionCallBackHandler)completion {
  611. NSLog(@"%s\n %@", __PRETTY_FUNCTION__, [JDFacade facade].deviceUUID);
  612. NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID,
  613. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  614. @"os_type": MOBILE_DEVICE_TYPE};
  615. NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];
  616. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  617. LoginModel *loginInfo = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:parameter
  618. modelClass:[LoginModel class] showLoadingView:YES];
  619. if (loginInfo) {
  620. [JDFacade facade].loginUser = loginInfo;
  621. }
  622. if (completion) {
  623. completion();
  624. }
  625. });
  626. }
  627. - (void)updateMainViewController {
  628. [self.mainViewController updateCurrentViewController];
  629. }
  630. - (void)loadURLExternalBrowser:(NSString *)URLString {
  631. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
  632. }
  633. - (void)alertCameraPermissionDisabled {
  634. NSString *message = MSG_CAMERA_DISABLE;
  635. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:message delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  636. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  637. if (buttonIndex == 0) {//OK
  638. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  639. [[UIApplication sharedApplication]openURL:settingsURL];
  640. }
  641. }];
  642. }
  643. #pragma mark - Debug
  644. - (void)showFlex {
  645. #ifndef PRODUCT_MODE
  646. [[FLEXManager sharedManager] showExplorer];
  647. #endif
  648. }
  649. - (BOOL)redirectNSLog {
  650. // Create log file
  651. NSDate *date = [NSDate date];
  652. NSDateFormatter *df = [CommonUtil dateFormatter];
  653. [df setDateFormat:@"yyyyMMddHHmmss"];
  654. NSString *sdate = [df stringFromDate:date];
  655. NSString *logPath = [NSString stringWithFormat:@"%@/log_%@.txt", NSTemporaryDirectory(), sdate];
  656. [@"" writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  657. id fileHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
  658. if (!fileHandle) {
  659. NSLog(@"Opening log failed");
  660. return NO;
  661. }
  662. // Redirect stderr
  663. int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
  664. if (!err) {
  665. NSLog(@"Couldn't redirect stderr");
  666. return NO;
  667. }
  668. return YES;
  669. }
  670. - (void)observeKeyboardRect {
  671. if (CGRectEqualToRect(gKeyboardRect, CGRectZero)) {
  672. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  673. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  674. }
  675. }
  676. - (void)keyboardWillShow:(NSNotification *)notification {
  677. NSDictionary *info = [notification userInfo];
  678. gKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  679. }
  680. - (void)keyboardWillHide:(NSNotification*)notification {
  681. gKeyboardRect = CGRectZero;
  682. }
  683. #pragma mark - Singleton
  684. + (JDFacade *)facade {
  685. static JDFacade *sharedJSFacade = nil;
  686. static dispatch_once_t onceToken;
  687. dispatch_once(&onceToken, ^{
  688. sharedJSFacade = [[self alloc] init];
  689. [sharedJSFacade observeKeyboardRect];
  690. });
  691. return sharedJSFacade;
  692. }
  693. - (id)init {
  694. if (self = [super init]) {
  695. }
  696. return self;
  697. }
  698. -(NSString *)getUrlWithCustID:(NSString *)str aditional:(NSString *)aditional {
  699. NSString *result = @"";
  700. if ([aditional isEmptyString]) {
  701. result = [NSString stringWithFormat:str, _loginUser.custId, aditional];
  702. }
  703. else {
  704. result = [NSString stringWithFormat:str, _loginUser.custId];
  705. }
  706. return result;
  707. }
  708. -(NSString *)getUrlWithCustAndGroupID:(NSString *)str aditional:(NSString *)aditional {
  709. NSString *result = @"";
  710. if ([aditional isEmptyString]) {
  711. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, aditional];
  712. }
  713. else {
  714. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId];
  715. }
  716. return result;
  717. }
  718. -(NSString *)getUrlWithCustAndGroupID:(NSString *)str arguments:(NSArray *)arguments
  719. {
  720. NSMutableArray *arr = [NSMutableArray array];
  721. arr[0] = _loginUser.custId;
  722. arr[1] = _loginUser.ctrtGrpId;
  723. if (arguments != nil) {
  724. int i = 2;
  725. for (NSString *str in arguments) {
  726. arr[i] = str;
  727. i++;
  728. }
  729. }
  730. return [self getUrlWithArr:str arguments:arr];
  731. }
  732. -(NSString *)getUrlWithArr:(NSString *)str arguments:(NSArray *)arguments {
  733. // NSRange range = NSMakeRange(0, [arguments count]);
  734. // NSMutableData* data = [NSMutableData dataWithLength:sizeof(id) * [arguments count]];
  735. // [arguments getObjects:(__unsafe_unretained id *)data.mutableBytes range:range];
  736. // NSString* result = [[NSString alloc] initWithFormat:str arguments:data.mutableBytes];
  737. return [str stringWithFormatWithArr:arguments];
  738. }
  739. -(NSString *)getUrlWithCustGroupIDAndMemberID:(NSString *)str {
  740. return [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, _loginUser.memberId];
  741. }
  742. -(NSString *)getUrlWithCustAndGroupIDAndInputMemId:(NSString *)str inputId:(NSString *)inputId{
  743. if ([inputId isEqualToString:@""]) {
  744. return [NSString stringWithFormat:str, _signUpUser.custId, _signUpUser.ctrtGrpId];
  745. } else {
  746. return [NSString stringWithFormat:str, _signUpUser.custId, _signUpUser.ctrtGrpId, inputId];
  747. }
  748. }
  749. @end