JDFacade.m 37 KB

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