JDFacade.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 "KeychainItemWrapper.h"
  13. #import "JDUUID.h"
  14. #import "CustomLoadingView.h"
  15. #import "CustomImageView.h"
  16. #import "CustomAlertView.h"
  17. #import "RequestHandler.h"
  18. //OpenSource
  19. #import "FLEXManager.h"
  20. #import "UIView+Toast.h"
  21. #import "JDProgressHUD.h"
  22. @interface JDFacade () {
  23. KeychainItemWrapper *_keychainItemWrapper;
  24. JDProgressHUD *_HUD;
  25. }
  26. @end
  27. @implementation JDFacade
  28. @synthesize tmpEmailId = _tmpEmailId;
  29. #pragma mark - Properties
  30. - (NSString *)deviceUUID {
  31. if (!_deviceUUID) {
  32. _deviceUUID = [[JDUUID UUIDHandler] getUUID];
  33. }
  34. return _deviceUUID;
  35. }
  36. - (NSString *)APNSToken {
  37. return _APNSToken ? _APNSToken : ksEmptyString;
  38. }
  39. - (NSString *)tmpEmailId {
  40. //FIXME : 다시 생각해바,
  41. NSString *enTmpEmailId = [self objectForKeyFromUserDefaults:USER_DEF_TMP_EMAIL];
  42. _tmpEmailId = [CypherUtil AES128Decrypt:enTmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  43. return _tmpEmailId ? _tmpEmailId : ksEmptyString;
  44. }
  45. - (void)setTmpEmailId:(NSString *)tmpEmailId {
  46. NSString *enTmpEmailId = [CypherUtil AES128Encrypt:tmpEmailId WithKey:[CommonUtil bundleIdentifier]];
  47. [self storeObjectToUserDefaults:enTmpEmailId forKey:USER_DEF_TMP_EMAIL];
  48. }
  49. - (void)setLoginHomeGroup:(HomeGroupModel *)loginHomeGroup {
  50. _loginHomeGroup = loginHomeGroup;
  51. _loginUser.homegrpId = _loginHomeGroup.homegrpId;
  52. [RequestHandler handler].homegrpId = _loginHomeGroup.homegrpId;
  53. }
  54. #pragma mark - View Facade
  55. - (AppDelegate *)appDelegate {
  56. return (AppDelegate *)[UIApplication sharedApplication].delegate;
  57. }
  58. #pragma mark - 화면 제어
  59. - (UIViewController *)currentViewController {
  60. id appDelegate = [UIApplication sharedApplication].delegate;
  61. UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
  62. if (vc.presentedViewController) {
  63. vc = vc.presentedViewController;
  64. if ([vc isKindOfClass:[UINavigationController class]]) {
  65. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  66. vc = [vcArray objectAtIndex:vcArray.count - 1];
  67. }
  68. return vc;
  69. }
  70. if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
  71. vc = vc.presentingViewController;
  72. }
  73. if ([vc isKindOfClass:[UINavigationController class]]) {
  74. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  75. vc = [vcArray objectAtIndex:vcArray.count - 1];
  76. }
  77. return vc;
  78. }
  79. - (id)viewControllerOnNaviationController:(Class)viewControllerClass {
  80. UIViewController *targetVc = nil;
  81. UINavigationController *navigationController = self.currentViewController.navigationController;
  82. if (!navigationController) {
  83. navigationController = (UINavigationController *)self.currentViewController.presentingViewController;
  84. }
  85. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  86. for (UIViewController *vc in navigationController.viewControllers) {
  87. if ([vc isKindOfClass:viewControllerClass]) {
  88. targetVc = vc;
  89. break;
  90. }
  91. }
  92. }
  93. return targetVc;
  94. }
  95. - (id)viewControllerOnPresentingViewController:(UIViewController *)pvc viewControllerClass:(Class)viewControllerClass {
  96. UIViewController *vc = pvc.presentingViewController;
  97. if (![vc isKindOfClass:viewControllerClass]) {
  98. vc = [self viewControllerOnPresentingViewController:vc viewControllerClass:viewControllerClass];
  99. }
  100. return vc;
  101. }
  102. #pragma mark - UserDefautls - Local Store
  103. - (void)storeObjectToUserDefaults:(id)object forKey:(NSString *)aKey {
  104. [[JDUserDefaults defaults] syncronizeObject:object forKey:aKey];
  105. }
  106. - (id)objectForKeyFromUserDefaults:(NSString *)aKey {
  107. return [[JDUserDefaults defaults] objectForKey:aKey];
  108. }
  109. #pragma mark - Alert & Loading
  110. - (void)loadIndicator:(BOOL)showIndicator allowUserInteraction:(BOOL)allowUserInteracton {
  111. UIWindow *mainWindow = [self appDelegate].window;
  112. //로딩시 터치 방지
  113. if(showIndicator) {
  114. dispatch_async(dispatch_get_main_queue(), ^{
  115. [[JDFacade facade].currentViewController.view endEditing:YES];
  116. UIView *topView = [[mainWindow subviews] lastObject];
  117. [CustomLoadingView showWithView:topView];
  118. mainWindow.userInteractionEnabled = allowUserInteracton;
  119. });
  120. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  121. } else {
  122. dispatch_async(dispatch_get_main_queue(), ^{
  123. [CustomLoadingView hide];
  124. mainWindow.userInteractionEnabled = allowUserInteracton;
  125. });
  126. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  127. }
  128. }
  129. - (void)showLoadingWhileExecutingBlock:(dispatch_block_t)block completionHandler:(JDFacadeCompletionCallBackHandler)handler {
  130. if (!_HUD) {
  131. _HUD = [JDProgressHUD progressHUDWithStyle:JGProgressHUDStyleExtraLight];
  132. }
  133. _HUD.textLabel.text = @"로딩 중";
  134. [_HUD showLoadingWhileExecutingBlock:block completionHandler:handler];
  135. }
  136. #pragma mark - Alert UI
  137. - (void)alert:(NSString *)message {
  138. [self.currentViewController.view endEditing:YES];
  139. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  140. [alert show];
  141. }
  142. - (void)retryAlert:(NSString *)message target:(id)target selector:(SEL)selector {
  143. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"재시도"];
  144. [alert show];
  145. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  146. if (buttonIndex == 1) {
  147. if ([target respondsToSelector:selector]) {
  148. [target performSelector:selector withObject:nil afterDelay:0.0f];
  149. }
  150. }
  151. }];
  152. }
  153. - (void)alert:(NSString *)message completionHander:(JDFacadeCompletionCallBackHandler)handler {
  154. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  155. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  156. if (handler) {
  157. handler();
  158. }
  159. }];
  160. }
  161. - (void)fireLocalNotification:(NSString *)message {
  162. NSLog(@"fireLocalNotification %@", message);
  163. NSDate *now = [NSDate date];
  164. UILocalNotification *localNotif = [[UILocalNotification alloc] init];
  165. localNotif.fireDate = now;
  166. NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
  167. localNotif.timeZone = timezone;
  168. localNotif.hasAction = YES;
  169. localNotif.alertBody = message;
  170. localNotif.alertAction = @"View";
  171. localNotif.soundName = UILocalNotificationDefaultSoundName;
  172. localNotif.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
  173. [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
  174. }
  175. - (void)toast:(NSString *)message {
  176. [[CommonUtil topView] makeToast:message];
  177. }
  178. #pragma mark - 화면이동 제어
  179. - (id)getRadioButtonStatus:(id)object {
  180. return objc_getAssociatedObject(object, ksCustomRadioButtonStatus);
  181. }
  182. - (void)setRadioButtonStatus:(id)status object:(id)object {
  183. objc_setAssociatedObject(object, ksCustomRadioButtonStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for radio box
  184. }
  185. - (id)getCheckBoxStatus:(id)object {
  186. return objc_getAssociatedObject(object, ksCustomCheckBoxStatus);
  187. }
  188. - (void)setCheckBoxStatus:(id)status object:(id)object {
  189. objc_setAssociatedObject(object, ksCustomCheckBoxStatus, status, OBJC_ASSOCIATION_COPY_NONATOMIC); //for check box
  190. }
  191. - (void)presentViewControllerByPush:(UIViewController *)vc {
  192. CATransition *transition = [CATransition animation];
  193. transition.duration = kfTransitionRightDur;
  194. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  195. transition.type = kCATransitionPush;
  196. transition.subtype = kCATransitionFromRight;
  197. [self.currentViewController.view.window.layer addAnimation:transition forKey:nil];
  198. [self.currentViewController presentViewController:vc animated:NO completion:nil];
  199. }
  200. - (void)presentViewControllerByPush:(UIViewController *)vc pvc:(UIViewController *)pvc {
  201. CATransition *transition = [CATransition animation];
  202. transition.duration = kfTransitionRightDur;
  203. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  204. transition.type = kCATransitionPush;
  205. transition.subtype = kCATransitionFromRight;
  206. [pvc.view.window.layer addAnimation:transition forKey:nil];
  207. [pvc presentViewController:vc animated:NO completion:nil];
  208. }
  209. - (UIViewController *)presentedViewController:(UIViewController *)vc {
  210. UIViewController *presentedViewController = vc.presentedViewController;
  211. if (presentedViewController) {
  212. return [self presentedViewController:presentedViewController];
  213. }
  214. return vc;
  215. }
  216. - (void)dismissViewControllerByPush:(UIViewController *)vc {
  217. CATransition *transition = [CATransition animation];
  218. transition.duration = kfTransitionRightDur;
  219. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  220. transition.type = kCATransitionPush;
  221. transition.subtype = kCATransitionFromLeft;
  222. UIViewController *presentedViewController = [self presentedViewController:vc];
  223. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  224. [vc dismissViewControllerAnimated:NO completion:nil];
  225. }
  226. - (void)dismissViewControllerByPush:(UIViewController *)vc completion:(JDFacadeCompletionCallBackHandler)completion {
  227. CATransition *transition = [CATransition animation];
  228. transition.duration = kfTransitionRightDur;
  229. transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  230. transition.type = kCATransitionPush;
  231. transition.subtype = kCATransitionFromLeft;
  232. UIViewController *presentedViewController = [self presentedViewController:vc];
  233. [presentedViewController.view.window.layer addAnimation:transition forKey:nil];
  234. [vc dismissViewControllerAnimated:NO completion:^{
  235. if (completion) {
  236. completion();
  237. }
  238. }];
  239. }
  240. - (void)dismissAllViewControllers {
  241. UIViewController *vc = self.currentViewController;
  242. if (vc.presentingViewController) {
  243. [vc dismissViewControllerAnimated:NO completion:^{
  244. [self dismissAllViewControllers];
  245. }];
  246. }
  247. }
  248. #pragma mark - UI Flow
  249. - (void)gotoLoginView {
  250. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  251. [JDFacade facade].appDelegate.window.rootViewController = vc;
  252. }
  253. //- (void)gotoLoginViewWithExpiring {
  254. // LoginViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  255. // [vc actionAfterLogout];
  256. //}
  257. //
  258. //- (void)logout {
  259. // LoginViewController *lvc = (LoginViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
  260. // [lvc requestLogout];
  261. //}
  262. //
  263. //- (void)loadInvitationView {
  264. // UIViewController *pvc = [JDFacade facade].currentViewController.presentedViewController;
  265. // if (!pvc) {
  266. // pvc = [JDFacade facade].currentViewController;
  267. // }
  268. //
  269. // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"InvitationListViewController" storyboardName:@"Main"];
  270. // [[JDFacade facade] presentViewControllerByPush:vc pvc:pvc];
  271. //}
  272. //
  273. //- (void)checkDefaultHome {
  274. // if (!self.loginUser) {//로그인이 안된 경우, 불필요함.
  275. // return;
  276. // }
  277. //
  278. // [self updateHomegrpListForLoginUser:^{
  279. // //1. 다른 홈이 있는지 확인 - 정렬순서대로 기본홈을 설정 - currentHome
  280. // if (self.loginUser.homegrpList && self.loginUser.homegrpList.count) {
  281. // self.loginHomeGroup = self.loginUser.homegrpList[0];
  282. // [self gotoWishMenu:KNMenuIdDashboard];
  283. // return;
  284. // }
  285. //
  286. // //2. 다른 홈이 없는 경우, - 홈만들기로 이동함.
  287. // CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:NSLocalizedString(@"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?", @"현재 참여 중인 홈이 없습니다\n새로운 홈 만들기를 시작할까요?") delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
  288. // [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  289. // if (buttonIndex == 0) {//OK
  290. // [self gotoStartHome:NO];
  291. // } else {
  292. // [self logout];
  293. // }
  294. // }];
  295. // }];
  296. //}
  297. - (void)gotoStartHome:(BOOL)canGoBack {
  298. // StartHomeViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"StartHomeViewController" storyboardName:@"SignUp"];
  299. // vc.canGoBack = canGoBack;
  300. // [[JDFacade facade] presentViewControllerByPush:vc pvc:self.currentViewController];
  301. }
  302. - (void)gotoWishMenu:(KNMenuId)menuId {
  303. [self gotoWishMenu:menuId completion:nil];
  304. }
  305. - (void)gotoWishMenu:(KNMenuId)menuId completion:(JDFacadeCompletionCallBackHandler)completion {
  306. self.wishMenuId = menuId;
  307. UIViewController *vc = self.appDelegate.window.rootViewController;
  308. if (vc.presentedViewController || (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen))){
  309. [vc dismissViewControllerAnimated:YES completion:nil];
  310. }
  311. // MenuViewController *mvc = [JDFacade facade].menuViewController;
  312. // [mvc gotoWishMenu:self.wishMenuId completion:completion];
  313. }
  314. - (void)updateHomegrpListForLoginUser:(JDFacadeCompletionCallBackHandler)completion {
  315. NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID};
  316. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  317. HomeGroupListModel *homegrpList = [[RequestHandler handler] sendSyncGetRequestAPIPath:API_GET_HOMEGROUP parameters:parameter
  318. modelClass:[HomeGroupListModel class] showLoadingView:YES];
  319. // NSLog(@"%s\n %@", __PRETTY_FUNCTION__, homegrpList);
  320. //홈그룹을 설정함.
  321. self.loginUser.homegrpList = homegrpList && homegrpList.homegrpList ? homegrpList.homegrpList : nil;
  322. //로그인 홈을 지정함.
  323. for (HomeGroupModel *homegrp in self.loginUser.homegrpList) {
  324. if ([self.loginUser.homegrpId isEqualToString:homegrp.homegrpId]) {
  325. self.loginHomeGroup = homegrp;
  326. break;
  327. }
  328. }
  329. // [[LocationHandler handler] resetAllMonitoredRegions]; //현재 앱이 구동 중이면, 위치 센서를 다시 등록해야함.
  330. // [[LocationHandler handler] registerGeofencingForHomeGroupIndex:0]; //모든 홈 그룹을 다시 모니터링 등록 - 루프
  331. if (completion) {
  332. completion();
  333. }
  334. });
  335. }
  336. - (void)updateLoginInfo:(JDFacadeCompletionCallBackHandler)completion {
  337. NSLog(@"%s\n %@", __PRETTY_FUNCTION__, [JDFacade facade].deviceUUID);
  338. NSDictionary *parameter = @{@"device_sn": [JDFacade facade].deviceUUID,
  339. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  340. @"os_type": MOBILE_DEVICE_TYPE};
  341. NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];
  342. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  343. LoginModel *loginInfo = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:parameter
  344. modelClass:[LoginModel class] showLoadingView:YES];
  345. if (loginInfo) {
  346. [JDFacade facade].loginUser = loginInfo;
  347. }
  348. if (completion) {
  349. completion();
  350. }
  351. });
  352. }
  353. - (void)alertLocationServiceDisabled {
  354. NSString *message = MSG_LOCATION_DISABLE;
  355. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소") message:message, nil];
  356. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  357. if (buttonIndex == 0) {//OK
  358. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  359. [[UIApplication sharedApplication]openURL:settingsURL];
  360. }
  361. }];
  362. }
  363. - (void)alertCameraPermissionDisabled {
  364. NSString *message = MSG_CAMERA_DISABLE;
  365. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소") message:message, nil];
  366. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  367. if (buttonIndex == 0) {//OK
  368. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  369. [[UIApplication sharedApplication]openURL:settingsURL];
  370. }
  371. }];
  372. }
  373. #pragma mark - Debug
  374. - (void)showFlex {
  375. [[FLEXManager sharedManager] showExplorer];
  376. }
  377. - (BOOL)redirectNSLog {
  378. // Create log file
  379. NSDate *date = [NSDate date];
  380. NSDateFormatter *df = [CommonUtil dateFormatter];
  381. [df setDateFormat:@"yyyyMMddHHmmss"];
  382. NSString *sdate = [df stringFromDate:date];
  383. NSString *logPath = [NSString stringWithFormat:@"%@/log_%@.txt", NSTemporaryDirectory(), sdate];
  384. [@"" writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  385. id fileHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
  386. if (!fileHandle) {
  387. NSLog(@"Opening log failed");
  388. return NO;
  389. }
  390. // Redirect stderr
  391. int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
  392. if (!err) {
  393. NSLog(@"Couldn't redirect stderr");
  394. return NO;
  395. }
  396. return YES;
  397. }
  398. #pragma mark - Singleton
  399. + (JDFacade *)facade {
  400. static JDFacade *sharedJSFacade = nil;
  401. static dispatch_once_t onceToken;
  402. dispatch_once(&onceToken, ^{
  403. sharedJSFacade = [[self alloc] init];
  404. });
  405. return sharedJSFacade;
  406. }
  407. - (id)init {
  408. if (self = [super init]) {
  409. }
  410. return self;
  411. }
  412. @end