JDFacade.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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. NSMutableDictionary *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. [alertController addAction:action];
  316. }
  317. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"취소" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  318. }];
  319. [alertController addAction:cancelAction];
  320. // NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:alertController.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:IPHONE_HEIGHT*.5f];
  321. // [alertController.view addConstraint:constraint];
  322. [alertController.view mas_makeConstraints:^(MASConstraintMaker *make) {
  323. make.height.lessThanOrEqualTo(@(IPHONE_HEIGHT*.5f));
  324. }];
  325. [target presentViewController:alertController animated:YES completion:nil];
  326. }
  327. - (void)fireLocalNotification:(NSString *)message {
  328. NSLog(@"fireLocalNotification %@", message);
  329. NSDate *now = [NSDate date];
  330. UILocalNotification *localNotif = [[UILocalNotification alloc] init];
  331. localNotif.fireDate = now;
  332. NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
  333. localNotif.timeZone = timezone;
  334. localNotif.hasAction = YES;
  335. localNotif.alertBody = message;
  336. localNotif.alertAction = @"View";
  337. localNotif.soundName = UILocalNotificationDefaultSoundName;
  338. localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
  339. [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
  340. }
  341. - (void)toast:(NSString *)message {
  342. [[CommonUtil topView] makeToast:message];
  343. }
  344. #pragma mark - CheckBox && Radiobutton Status
  345. - (id)getRadioButtonStatus:(id)object {
  346. if (!object)
  347. return @NO;
  348. return objc_getAssociatedObject(object, ksCustomRadioButtonStatus);
  349. }
  350. - (void)setRadioButtonStatus:(id)status object:(id)object {
  351. if (!object)
  352. return;
  353. objc_setAssociatedObject(object, ksCustomRadioButtonStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for radio box
  354. }
  355. - (id)getCheckBoxStatus:(id)object {
  356. if (!object)
  357. return @NO;
  358. return objc_getAssociatedObject(object, ksCustomCheckBoxStatus);
  359. }
  360. - (void)setCheckBoxStatus:(id)status object:(id)object {
  361. if (!object)
  362. return;
  363. objc_setAssociatedObject(object, ksCustomCheckBoxStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for check box
  364. }
  365. #pragma mark - 화면이동 제어
  366. - (void)dismissModalStack:(BOOL)animated completion:(JDFacadeCompletionCallBackHandler)completion {
  367. UIViewController *vc = self.currentViewController;
  368. while (vc.presentingViewController) {
  369. vc = vc.presentingViewController;
  370. }
  371. CATransition *transition = [CATransition animation];
  372. transition.duration = kfTransitionRightDur;
  373. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  374. transition.type = kCATransitionMoveIn;
  375. transition.subtype = kCATransitionFromBottom;
  376. [vc.view.window.layer addAnimation:transition forKey:nil];
  377. [vc dismissViewControllerAnimated:NO completion:^{
  378. if (completion) {
  379. completion();
  380. }
  381. }];
  382. }
  383. - (void)presentViewControllerByPush:(UIViewController *)vc {
  384. CATransition *transition = [CATransition animation];
  385. transition.duration = kfTransitionRightDur;
  386. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  387. transition.type = kCATransitionPush;
  388. transition.subtype = kCATransitionFromRight;
  389. [self.currentViewController.view.window.layer addAnimation:transition forKey:nil];
  390. [self.currentViewController presentViewController:vc animated:NO completion:nil];
  391. }
  392. - (void)presentViewControllerByPush:(UIViewController *)vc pvc:(UIViewController *)pvc {
  393. CATransition *transition = [CATransition animation];
  394. transition.duration = kfTransitionRightDur;
  395. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  396. transition.type = kCATransitionPush;
  397. transition.subtype = kCATransitionFromRight;
  398. [pvc.view.window.layer addAnimation:transition forKey:nil];
  399. [pvc presentViewController:vc animated:NO completion:nil];
  400. }
  401. - (UIViewController *)presentedViewController:(UIViewController *)vc {
  402. UIViewController *presentedViewController = vc.presentedViewController;
  403. if (presentedViewController) {
  404. return [self presentedViewController:presentedViewController];
  405. }
  406. return vc;
  407. }
  408. - (void)dismissViewControllerByPush:(UIViewController *)vc {
  409. CATransition *transition = [CATransition animation];
  410. transition.duration = kfTransitionRightDur;
  411. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  412. transition.type = kCATransitionPush;
  413. transition.subtype = kCATransitionFromBottom;
  414. UIViewController *presentedViewController = [self presentedViewController:vc];
  415. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  416. [vc dismissViewControllerAnimated:NO completion:nil];
  417. }
  418. - (void)dismissViewControllerByPush:(UIViewController *)vc completion:(JDFacadeCompletionCallBackHandler)completion {
  419. CATransition *transition = [CATransition animation];
  420. transition.duration = kfTransitionRightDur;
  421. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  422. transition.type = kCATransitionPush;
  423. transition.subtype = kCATransitionFromLeft;
  424. UIViewController *presentedViewController = [self presentedViewController:vc];
  425. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  426. [vc dismissViewControllerAnimated:NO completion:^{
  427. if (completion) {
  428. completion();
  429. }
  430. }];
  431. }
  432. - (void)dismissAllViewControllers {
  433. UIViewController *vc = self.currentViewController;
  434. if (vc.presentingViewController) {
  435. [vc dismissViewControllerAnimated:NO completion:^{
  436. [self dismissAllViewControllers];
  437. }];
  438. }
  439. }
  440. #pragma mark - Biz Logic
  441. - (void)requestPollingHomeHubStatusInBackground {
  442. //schedul timer.
  443. if (!_homehubBackgroundTimer) {
  444. [self requestPollingHomeHubStatus:^{
  445. _homehubBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestPollingHomeHubStatus) userInfo:nil repeats:YES];
  446. }];
  447. }
  448. }
  449. - (void)requestPollingHomeHubStatus {
  450. [self requestPollingHomeHubStatus:nil];
  451. }
  452. - (void)requestPollingHomeHubStatus:(JDFacadeCompletionCallBackHandler)completion {
  453. NSString *path = API_GET_DEVICE_HOMEHUB_STATUS;
  454. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  455. DeviceModel *homehub = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  456. modelClass:[DeviceModel class] showLoadingView:NO];
  457. if (homehub && homehub.onlineState && ![homehub.onlineState isEmptyString]) {
  458. [JDFacade facade].loginUser.homehubOnlineState = homehub.onlineState;
  459. [JDFacade facade].loginUser.homehubCreateDatetime = homehub.createDatetime;
  460. } else {
  461. [JDFacade facade].loginUser.homehubDeviceId = nil;
  462. [JDFacade facade].loginUser.homehubOnlineState = nil;
  463. [JDFacade facade].loginUser.homehubCreateDatetime = nil;
  464. }
  465. [_mainViewController updateHomeHubStatusToChildViewController];
  466. //update global - homehub state
  467. if ([[JDFacade facade].currentViewController isKindOfClass:[HomeHubViewController class]]) {
  468. HomeHubViewController *vc = (HomeHubViewController *)[JDFacade facade].currentViewController;
  469. [vc updateHomeHubStatus];
  470. }
  471. #ifdef DEBUG_MODE
  472. NSLogInfo(@"==########== homehub state = %@ ==########==", [JDFacade facade].loginUser.homehubOnlineState);
  473. #endif
  474. if (completion) {
  475. completion();
  476. }
  477. });
  478. }
  479. #pragma mark - UI Flow
  480. - (void)gotoLoginView {
  481. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  482. [[JDFacade facade].appDelegate.window setRootViewController:vc];
  483. }
  484. //- (void)gotoLoginViewWithExpiring {
  485. // LoginViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  486. // [vc actionAfterLogout];
  487. //}
  488. //
  489. - (void)logout {
  490. LoginViewController *lvc = (LoginViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  491. [lvc requestLogout];
  492. }
  493. - (void)loadInvitationView {
  494. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"InvitationListViewController" storyboardName:@"Main"];
  495. [self.currentViewController presentViewController:vc animated:YES completion:nil];
  496. }
  497. //- (void)checkDefaultHome {
  498. // if (!self.loginUser) {//로그인이 안된 경우, 불필요함.
  499. // return;
  500. // }
  501. //
  502. // [self updateHomegrpListForLoginUser:^{
  503. // //1. 다른 홈이 있는지 확인 - 정렬순서대로 기본홈을 설정 - currentHome
  504. // if (self.loginUser.homegrpList && self.loginUser.homegrpList.count) {
  505. // self.loginHomeGroup = self.loginUser.homegrpList[0];
  506. // [self gotoWishMenu:KNMenuIdDashboard];
  507. // return;
  508. // }
  509. //
  510. // //2. 다른 홈이 없는 경우, - 홈만들기로 이동함.
  511. // CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:NSLocalizedString(@"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?", @"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?") delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  512. // [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  513. // if (buttonIndex == 0) {//OK
  514. // [self gotoStartHome:NO];
  515. // } else {
  516. // [self logout];
  517. // }
  518. // }];
  519. // }];
  520. //}
  521. - (void)gotoStartHome:(BOOL)canGoBack {
  522. // StartHomeViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"StartHomeViewController" storyboardName:@"SignUp"];
  523. // vc.canGoBack = canGoBack;
  524. // [[JDFacade facade] presentViewControllerByPush:vc pvc:self.currentViewController];
  525. }
  526. - (void)gotoWishMenu:(KNMenuId)menuId {
  527. [self gotoWishMenu:menuId completion:nil];
  528. }
  529. - (void)gotoWishMenu:(KNMenuId)menuId completion:(JDFacadeCompletionCallBackHandler)completion {
  530. self.wishMenuId = menuId;
  531. switch (self.wishMenuId) {
  532. case KNMenuIdDashboard: {
  533. // [_mainViewController btnCollapseTouched:nil];
  534. [[JDFacade facade] requestPollingHomeHubStatus:^{
  535. [[JDFacade facade] dismissModalStack:YES completion:nil];
  536. }];
  537. }
  538. break;
  539. case KNMenuIdThings: {
  540. [[JDFacade facade] dismissModalStack:YES completion:^{
  541. [_mainViewController loadThingsViewController];
  542. }];
  543. }
  544. break;
  545. case KNMenuIdRules: {
  546. [[JDFacade facade] dismissModalStack:YES completion:^{
  547. [_mainViewController loadRulesViewController];
  548. }];
  549. }
  550. break;
  551. case KNMenuIdHomeMember: {
  552. [[JDFacade facade] dismissModalStack:YES completion:^{
  553. [_mainViewController loadMembersViewController];
  554. }];
  555. }
  556. break;
  557. case KNMenuIdManagement: {
  558. [[JDFacade facade] dismissModalStack:YES completion:^{
  559. [_mainViewController loadManagementViewController];
  560. }];
  561. }
  562. break;
  563. default:
  564. break;
  565. }
  566. }
  567. - (void)gotoHomeHubRegistration {
  568. // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubStartViewController" storyboardName:@"HomeHub"];
  569. //
  570. // vc.providesPresentationContextTransitionStyle = YES;
  571. // vc.definesPresentationContext = YES;
  572. //
  573. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  574. //
  575. // [self.currentViewController presentViewController:vc animated:NO completion:nil];
  576. }
  577. //- (void)updateHomegrpListForLoginUser:(JDFacadeCompletionCallBackHandler)completion {
  578. //
  579. // NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID};
  580. //
  581. // dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  582. // HomeGroupListModel *homegrpList = [[RequestHandler handler] sendSyncGetRequestAPIPath:API_GET_HOMEGROUP parameters:parameter
  583. // modelClass:[HomeGroupListModel class] showLoadingView:YES];
  584. //
  585. //
  586. // // NSLog(@"%s\n %@", __PRETTY_FUNCTION__, homegrpList);
  587. // //홈그룹을 설정함.
  588. // self.loginUser.homegrpList = homegrpList && homegrpList.homegrpList ? homegrpList.homegrpList : nil;
  589. //
  590. // //로그인 홈을 지정함.
  591. // for (HomeGroupModel *homegrp in self.loginUser.homegrpList) {
  592. // if ([self.loginUser.homegrpId isEqualToString:homegrp.homegrpId]) {
  593. // self.loginHomeGroup = homegrp;
  594. // break;
  595. // }
  596. // }
  597. //
  598. //// [[LocationHandler handler] resetAllMonitoredRegions]; //현재 앱이 구동 중이면, 위치 센서를 다시 등록해야함.
  599. //// [[LocationHandler handler] registerGeofencingForHomeGroupIndex:0]; //모든 홈 그룹을 다시 모니터링 등록 - 루프
  600. //
  601. // if (completion) {
  602. // completion();
  603. // }
  604. // });
  605. //}
  606. - (void)updateLoginInfo:(JDFacadeCompletionCallBackHandler)completion {
  607. NSLog(@"%s\n %@", __PRETTY_FUNCTION__, [JDFacade facade].deviceUUID);
  608. NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID,
  609. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  610. @"os_type": MOBILE_DEVICE_TYPE};
  611. NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];
  612. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  613. LoginModel *loginInfo = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:parameter
  614. modelClass:[LoginModel class] showLoadingView:YES];
  615. if (loginInfo) {
  616. [JDFacade facade].loginUser = loginInfo;
  617. }
  618. if (completion) {
  619. completion();
  620. }
  621. });
  622. }
  623. - (void)updateMainViewController {
  624. [self.mainViewController updateCurrentViewController];
  625. }
  626. - (void)loadURLExternalBrowser:(NSString *)URLString {
  627. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
  628. }
  629. - (void)alertCameraPermissionDisabled {
  630. NSString *message = MSG_CAMERA_DISABLE;
  631. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:message delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  632. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  633. if (buttonIndex == 0) {//OK
  634. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  635. [[UIApplication sharedApplication]openURL:settingsURL];
  636. }
  637. }];
  638. }
  639. #pragma mark - Debug
  640. - (void)showFlex {
  641. #ifndef PRODUCT_MODE
  642. [[FLEXManager sharedManager] showExplorer];
  643. #endif
  644. }
  645. - (BOOL)redirectNSLog {
  646. // Create log file
  647. NSDate *date = [NSDate date];
  648. NSDateFormatter *df = [CommonUtil dateFormatter];
  649. [df setDateFormat:@"yyyyMMddHHmmss"];
  650. NSString *sdate = [df stringFromDate:date];
  651. NSString *logPath = [NSString stringWithFormat:@"%@/log_%@.txt", NSTemporaryDirectory(), sdate];
  652. [@"" writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  653. id fileHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
  654. if (!fileHandle) {
  655. NSLog(@"Opening log failed");
  656. return NO;
  657. }
  658. // Redirect stderr
  659. int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
  660. if (!err) {
  661. NSLog(@"Couldn't redirect stderr");
  662. return NO;
  663. }
  664. return YES;
  665. }
  666. - (void)observeKeyboardRect {
  667. if (CGRectEqualToRect(gKeyboardRect, CGRectZero)) {
  668. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  669. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  670. }
  671. }
  672. - (void)keyboardWillShow:(NSNotification *)notification {
  673. NSDictionary *info = [notification userInfo];
  674. gKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  675. }
  676. - (void)keyboardWillHide:(NSNotification*)notification {
  677. gKeyboardRect = CGRectZero;
  678. }
  679. #pragma mark - Singleton
  680. + (JDFacade *)facade {
  681. static JDFacade *sharedJSFacade = nil;
  682. static dispatch_once_t onceToken;
  683. dispatch_once(&onceToken, ^{
  684. sharedJSFacade = [[self alloc] init];
  685. [sharedJSFacade observeKeyboardRect];
  686. });
  687. return sharedJSFacade;
  688. }
  689. - (id)init {
  690. if (self = [super init]) {
  691. }
  692. return self;
  693. }
  694. -(NSString *)getUrlWithCustID:(NSString *)str aditional:(NSString *)aditional {
  695. NSString *result = @"";
  696. if ([aditional isEmptyString]) {
  697. result = [NSString stringWithFormat:str, _loginUser.custId, aditional];
  698. }
  699. else {
  700. result = [NSString stringWithFormat:str, _loginUser.custId];
  701. }
  702. return result;
  703. }
  704. -(NSString *)getUrlWithCustAndGroupID:(NSString *)str aditional:(NSString *)aditional {
  705. NSString *result = @"";
  706. if ([aditional isEmptyString]) {
  707. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, aditional];
  708. }
  709. else {
  710. result = [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId];
  711. }
  712. return result;
  713. }
  714. -(NSString *)getUrlWithCustAndGroupID:(NSString *)str arguments:(NSArray *)arguments
  715. {
  716. NSMutableArray *arr = [NSMutableArray array];
  717. arr[0] = _loginUser.custId;
  718. arr[1] = _loginUser.ctrtGrpId;
  719. if (arguments != nil) {
  720. int i = 2;
  721. for (NSString *str in arguments) {
  722. arr[i] = str;
  723. i++;
  724. }
  725. }
  726. return [self getUrlWithArr:str arguments:arr];
  727. }
  728. -(NSString *)getUrlWithArr:(NSString *)str arguments:(NSArray *)arguments {
  729. // NSRange range = NSMakeRange(0, [arguments count]);
  730. // NSMutableData* data = [NSMutableData dataWithLength:sizeof(id) * [arguments count]];
  731. // [arguments getObjects:(__unsafe_unretained id *)data.mutableBytes range:range];
  732. // NSString* result = [[NSString alloc] initWithFormat:str arguments:data.mutableBytes];
  733. return [str stringWithFormatWithArr:arguments];
  734. }
  735. -(NSString *)getUrlWithCustGroupIDAndMemberID:(NSString *)str {
  736. return [NSString stringWithFormat:str, _loginUser.custId, _loginUser.ctrtGrpId, _loginUser.memberId];
  737. }
  738. -(NSString *)getUrlWithCustAndGroupIDAndInputMemId:(NSString *)str inputId:(NSString *)inputId{
  739. if ([inputId isEqualToString:@""]) {
  740. return [NSString stringWithFormat:str, _signUpUser.custId, _signUpUser.ctrtGrpId];
  741. } else {
  742. return [NSString stringWithFormat:str, _signUpUser.custId, _signUpUser.ctrtGrpId, inputId];
  743. }
  744. }
  745. @end