CommonUtil.m 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. //
  2. // CommonUtil.m
  3. // JasonDevelop
  4. //
  5. // Created by Jason Lee on 2/14/14.
  6. // Copyright (c) jasondevelop. All rights reserved.
  7. //
  8. @import CoreTelephony.CTCarrier;
  9. @import CoreTelephony.CTCallCenter;
  10. @import CoreTelephony.CTCall;
  11. @import CoreTelephony.CTTelephonyNetworkInfo;
  12. #import "Common.h"
  13. #import "CommonUtil.h"
  14. #import "SortDictionary.h"
  15. #import "UIDeviceUtil.h"
  16. #define ksEmptyString @""
  17. @implementation CommonUtil
  18. #pragma mark - System Util
  19. + (NSString *)applicationVersion {
  20. NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
  21. // CGFloat version = [[[UIDevice currentDevice] ] floatValue];
  22. // CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
  23. return strVersion;
  24. }
  25. + (NSString *)applicationShortVersion {
  26. NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  27. // CGFloat version = [[[UIDevice currentDevice] ] floatValue];
  28. // CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
  29. return strVersion;
  30. }
  31. + (NSString *)bundleIdentifier {
  32. return [[NSBundle mainBundle] bundleIdentifier];
  33. }
  34. + (CGFloat)deviceSystemVersion {
  35. static NSUInteger _deviceSystemVersion = -1.0f;
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. _deviceSystemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
  39. });
  40. return _deviceSystemVersion;
  41. }
  42. + (NSString *)uniqueIdentifier {
  43. //uuid 로 변경
  44. NSString *identifier = ksEmptyString;
  45. // NSString *identifier = [[OSUserDefaults defaults] objectForKey:@"MAC_ADD"];
  46. //
  47. // if ([identifier length] == 0 || [identifier isEqual:ksEmptyString]) {
  48. // CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  49. // NSString *string = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
  50. //
  51. // [[OSUserDefaults defaults] setObject:string forKey:@"MAC_ADD"];
  52. // [[OSUserDefaults defaults] synchronize];
  53. // identifier = string;
  54. // }
  55. NSLog(@"===identifier===%@", identifier);
  56. return identifier;
  57. }
  58. + (NSString *)deviceName {//////////////////
  59. return [UIDevice currentDevice].name;
  60. }
  61. + (CGFloat)hardwareVersion {
  62. return [UIDeviceUtil hardwareNumber:[UIDeviceUtil hardware]];
  63. }
  64. + (NSUInteger)hardware {
  65. return [UIDeviceUtil hardware];
  66. }
  67. + (void)showCurrentDevice {
  68. UIDevice *device = [UIDevice currentDevice];
  69. NSMutableString *print = [NSMutableString new];
  70. [print appendFormat:@"\n%@\n", device.name];
  71. [print appendFormat:@"%@\n", device.systemName];
  72. [print appendFormat:@"%@\n", device.model];
  73. [print appendFormat:@"%@\n", device.localizedModel];
  74. [print appendFormat:@"%zd\n", device.userInterfaceIdiom];
  75. [print appendFormat:@"%@\n", [UIDeviceUtil hardwareSimpleDescription]];
  76. }
  77. #pragma makr - Locale
  78. + (NSString *)countryCode {
  79. return [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
  80. }
  81. #pragma mark - Network Util
  82. + (BOOL)roamingCheck {
  83. CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
  84. CTCarrier *carrier = [networkInfo subscriberCellularProvider];
  85. NSString *carrierName = [carrier carrierName]; //통신사를 받아올 수 있다.
  86. NSLog(@"Carrier: %@", carrierName);
  87. NSString *mnc = [carrier mobileNetworkCode]; //통신사를 받아올 수 있다.
  88. NSLog(@"mnc: %@", mnc);
  89. NSString *mcc = [carrier mobileCountryCode]; // 국가코드를 받아올 수 있다.
  90. NSLog(@"Mobile Country Code (MCC): %@", mcc);
  91. BOOL network = NO;
  92. if ([mnc isEqualToString:@"05"] || [mnc isEqualToString:@"06"] || [mnc isEqualToString:@"08"] ) { //mnc code
  93. if ([mcc isEqualToString:@"450"]) { //국가 코드
  94. network = YES;
  95. }
  96. }
  97. return network;
  98. }
  99. + (BOOL)isOnPhoneCall {
  100. CTCallCenter *callCenter = [[CTCallCenter alloc] init];
  101. for (CTCall *call in callCenter.currentCalls) {
  102. if (call.callState == CTCallStateConnected) {
  103. return YES;
  104. }
  105. }
  106. return NO;
  107. }
  108. #pragma mark - File Util
  109. +(NSString*)getPath:(NSString *)lastPath {
  110. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  111. NSString *documentsDirectory= [paths objectAtIndex:0];
  112. return [documentsDirectory stringByAppendingPathComponent:lastPath];
  113. }
  114. +(BOOL)isExistFile:(NSString*)filePath {
  115. BOOL isExist = NO;
  116. NSFileManager *fileManager = [NSFileManager defaultManager];
  117. if ([fileManager fileExistsAtPath:filePath])
  118. isExist = YES;
  119. else
  120. isExist = NO;
  121. return isExist;
  122. }
  123. + (BOOL)createFile:(NSString*)filePath {
  124. BOOL bCreate = NO;
  125. NSLog(@"document file path : %@", filePath);
  126. //파일의 존재 유무 검사 및 없으면 생성
  127. NSFileManager *fileManager = [NSFileManager defaultManager];
  128. BOOL isFile = [fileManager fileExistsAtPath:filePath];
  129. if (isFile | [fileManager createFileAtPath:filePath contents:nil attributes:nil]){
  130. bCreate = YES;
  131. }else{
  132. bCreate = NO;
  133. }
  134. return bCreate;
  135. }
  136. + (BOOL)deleteFile:(NSString *)fileName {
  137. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  138. NSString *filepath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], fileName];
  139. NSFileManager *fileManager = [NSFileManager defaultManager];
  140. [fileManager removeItemAtPath:filepath error:nil];
  141. return YES;
  142. }
  143. #pragma mark - UI Util
  144. + (id)instantiateViewControllerWithIdentifier:(NSString *)identifier storyboardName:(NSString *)storyboardName
  145. {
  146. UIStoryboard *sb = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
  147. return [sb instantiateViewControllerWithIdentifier:identifier];
  148. }
  149. + (UIViewController *)currentViewController {
  150. id appDelegate = [UIApplication sharedApplication].delegate;
  151. UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
  152. if (vc.presentedViewController) {
  153. while (vc.presentedViewController) {
  154. vc = vc.presentedViewController;
  155. }
  156. if ([vc isKindOfClass:[UINavigationController class]]) {
  157. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  158. vc = [vcArray objectAtIndex:vcArray.count - 1];
  159. }
  160. return vc;
  161. }
  162. if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
  163. vc = vc.presentingViewController;
  164. }
  165. if ([NSClassFromString(@"ECSlidingViewController") class] && [vc isKindOfClass:[NSClassFromString(@"ECSlidingViewController") class]]) {
  166. id slideController = vc;
  167. vc = (UINavigationController *)[slideController topViewController];
  168. }
  169. if ([vc isKindOfClass:[UINavigationController class]]) {
  170. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  171. vc = [vcArray objectAtIndex:vcArray.count - 1];
  172. }
  173. return vc;
  174. }
  175. + (UIView *)topView
  176. {
  177. UIView *topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
  178. while ([topView isKindOfClass:NSClassFromString(@"UITransitionView")]) {
  179. topView = [[topView subviews] lastObject];
  180. }
  181. if ([topView isKindOfClass:NSClassFromString(@"CustomLoadingView")]) {
  182. topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
  183. topView = [topView subviews][topView.subviews.count - 2];
  184. }
  185. topView = topView == nil ? [[UIApplication sharedApplication] keyWindow] : topView;
  186. return topView;
  187. }
  188. + (CGRect)mainScreenBounds {
  189. CGRect screenRect = [UIScreen mainScreen].bounds;
  190. return screenRect;
  191. }
  192. //해당 컨테이너로부터 해당 객체의 중앙 지점을 연산하여 반환함.
  193. + (CGRect)getCenterPosition:(id)object fromContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
  194. CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
  195. if (object && container) {
  196. CGRect cframe = [container frame];
  197. CGRect oframe = [object frame];
  198. float nHeight = hasNavigationBar ? 44.0 : 0;
  199. float tHeight = hasTabBar ? 59.0 : 0;
  200. float x = ((cframe.size.width - oframe.size.width) / 2);
  201. float y = (cframe.size.height - (oframe.size.height - nHeight - tHeight)) / 2;
  202. frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
  203. }
  204. return frame;
  205. }
  206. + (CGRect)centerRect:(id)object fromContainer:(id)container {
  207. CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
  208. if (object && container) {
  209. CGRect cframe = [container frame];
  210. CGRect oframe = [object frame];
  211. float x = ((cframe.size.width - oframe.size.width) / 2);
  212. float y = (cframe.size.height - (oframe.size.height)) / 2;
  213. frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
  214. }
  215. return frame;
  216. }
  217. //해당 객체를 해당 컨테이너의 중앙(가로*세로)에 위치시킴.
  218. + (void)moveToCenter:(id)object withContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
  219. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:hasNavigationBar hasTabBar:hasTabBar];
  220. UIView *oView = (UIView *)object;
  221. [oView setFrame:rect];
  222. }
  223. //해당 객체를 해당 컨테이너의 중앙(가로)에 위치시킴.
  224. + (void)moveToCenterHorizon:(id)object withContainer:(id)container {
  225. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
  226. CGRect oframe = [object frame];
  227. oframe.origin.x = rect.origin.x;
  228. UIView *oView = (UIView *)object;
  229. [oView setFrame:oframe];
  230. }
  231. //해당 객체를 해당 컨테이너의 중앙(세로)에 위치시킴.
  232. + (void)moveToCenterVertical:(id)object withContainer:(id)container {
  233. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
  234. CGRect oframe = [object frame];
  235. oframe.origin.y = rect.origin.y;
  236. UIView *oView = (UIView *)object;
  237. [oView setFrame:oframe];
  238. }
  239. + (CGSize)sizeWithString:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)constrainedToSize lineBreakMode:(NSLineBreakMode)lineBreakMode {
  240. CGSize size = CGSizeZero;
  241. if (IOS_VERSION >= 7.0f) {
  242. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  243. CGRect rect = [attributedText boundingRectWithSize:(CGSize){constrainedToSize.width, CGFLOAT_MAX}
  244. options:NSStringDrawingUsesLineFragmentOrigin
  245. context:nil];
  246. size = rect.size;
  247. }
  248. return size;
  249. }
  250. + (float)sizeWithStringHeight:(NSString *)text font:(UIFont *)font constrainedToSize:(float)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
  251. float size = 0;
  252. if (IOS_VERSION >= 7.0f) {
  253. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  254. CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
  255. options:NSStringDrawingUsesLineFragmentOrigin
  256. context:nil];
  257. size = rect.size.height;
  258. }
  259. return size;
  260. }
  261. + (CGFloat)getLabelRealWidth:(UILabel *)label fixedWidth:(CGFloat)fixedWidth {
  262. CGFloat width = 0.0f;
  263. CGRect oriRect = label.frame;
  264. CGRect chRect = label.frame;
  265. chRect.size.width = fixedWidth;
  266. label.frame = chRect;
  267. [label sizeToFit];
  268. width = label.frame.size.width;
  269. label.frame = oriRect;
  270. return width;
  271. }
  272. + (CGFloat)getLabelRealHeight:(UILabel *)label {
  273. CGFloat height = 0.0f;
  274. CGRect oriRect = label.frame;
  275. [label sizeToFit];
  276. height = label.frame.size.height;
  277. label.frame = oriRect;
  278. return height;
  279. }
  280. + (CGSize)getLabelRealSize:(UILabel *)label fixedWdith:(CGFloat)fixedWidth {
  281. CGFloat width = [CommonUtil getLabelRealWidth:label fixedWidth:fixedWidth];
  282. CGFloat height = [CommonUtil getLabelRealHeight:label];
  283. return CGSizeMake(width, height);
  284. }
  285. + (CGSize)getSizeFromString:(NSString *)string font:(UIFont *)font width:(CGFloat)fixedWidth {
  286. if ([string isEqualToString:ksEmptyString]) {
  287. return CGSizeZero;
  288. }
  289. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  290. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  291. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:context];
  292. r = CGRectIntegral(r);
  293. return r.size;
  294. }
  295. + (CGSize)getSizeFromAttributeString:(NSAttributedString *)string width:(CGFloat)fixedWidth {
  296. if ([string.string isEqualToString:ksEmptyString]) {
  297. return CGSizeZero;
  298. }
  299. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  300. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  301. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin context:context];
  302. r = CGRectIntegral(r);
  303. return r.size;
  304. }
  305. /**
  306. NIB에서 해당 뷰를 로드함.
  307. @return NSArray * 뷰어레이
  308. */
  309. + (NSArray *)nibViews:(NSString *)nibName {
  310. UINib *nib = [UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]];
  311. return [nib instantiateWithOwner:nil options:nil];
  312. }
  313. #pragma mark - Date Util
  314. + (NSCalendar *)calendar {
  315. NSCalendar *cal = [NSCalendar currentCalendar];
  316. [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
  317. return cal;
  318. }
  319. + (NSDateFormatter *)dateFormatter {
  320. static NSDateFormatter *__shareDateFormatter = nil;
  321. static dispatch_once_t onceToken;
  322. dispatch_once(&onceToken, ^{
  323. __shareDateFormatter = [[NSDateFormatter alloc] init];
  324. NSLocale *locale = [NSLocale currentLocale];
  325. [__shareDateFormatter setLocale:locale];
  326. });
  327. return __shareDateFormatter;
  328. }
  329. + (NSString *)currentDate {
  330. NSDateFormatter *df = [CommonUtil dateFormatter];
  331. df.dateFormat = @"YYYY.MM.dd";
  332. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  333. return title;
  334. }
  335. + (NSString *)currentMonth {
  336. NSDateFormatter *df = [CommonUtil dateFormatter];
  337. df.dateFormat = @"YYYY.MM";
  338. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  339. return title;
  340. }
  341. + (NSDateComponents *)dateComponents:(NSDate *)date {
  342. NSCalendar *calendar = [CommonUtil calendar];
  343. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  344. NSCalendarUnitMonth |
  345. NSCalendarUnitDay |
  346. NSCalendarUnitHour |
  347. NSCalendarUnitMinute|
  348. NSCalendarUnitSecond|
  349. NSCalendarUnitTimeZone) fromDate:date];
  350. return components;
  351. }
  352. + (NSDateComponents *)dateComponents:(NSDate *)date timezone:(NSTimeZone *)timezone {
  353. NSCalendar *calendar = [CommonUtil calendar];
  354. [calendar setTimeZone:timezone];
  355. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  356. NSCalendarUnitMonth |
  357. NSCalendarUnitDay |
  358. NSCalendarUnitHour |
  359. NSCalendarUnitMinute|
  360. NSCalendarUnitSecond|
  361. NSCalendarUnitTimeZone) fromDate:date];
  362. return components;
  363. }
  364. //Date객체를 String객체로 전환
  365. + (NSString *)stringFromDate:(NSDate *)date {
  366. NSDateFormatter *df = [CommonUtil dateFormatter];
  367. df.dateFormat = @"YYYY/MM/dd";
  368. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  369. }
  370. + (NSString *)stringFromDateTime:(NSDate *)date {
  371. NSDateFormatter *df = [CommonUtil dateFormatter];
  372. df.dateFormat = @"yyyyMMddHHmmss";
  373. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  374. }
  375. + (NSString *)birthStringFromDate:(NSDate *)date {
  376. NSDateFormatter *df = [CommonUtil dateFormatter];
  377. df.dateFormat = @"YYYYMMdd";
  378. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  379. }
  380. + (NSString *)stringFromDate2:(NSDate *)date {
  381. NSDateFormatter *df = [CommonUtil dateFormatter];
  382. df.dateFormat = @"YYYY-MM-dd";
  383. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  384. }
  385. + (NSString *)stringFromString:(NSString *)dateString {
  386. NSDateComponents *components = [CommonUtil dateComponentsFromString:dateString];
  387. return [CommonUtil stringFromDateComponents:components];
  388. }
  389. + (NSDateComponents *)dateComponentsFromString:(NSString *)dateString {
  390. NSDateComponents *dateComp = nil;
  391. if (dateString && dateString.length == 6) {//19990101 타입
  392. dateComp = [[NSDateComponents alloc] init];
  393. dateComp.year = [[dateString substringToIndex:4] intValue];
  394. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  395. } else if (dateString && dateString.length == 8) {//19990101 타입
  396. dateComp = [[NSDateComponents alloc] init];
  397. dateComp.year = [[dateString substringToIndex:4] intValue];
  398. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  399. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  400. } else if (dateString && dateString.length == 14) {//19990101010101 타입
  401. dateComp = [[NSDateComponents alloc] init];
  402. dateComp.year = [[dateString substringToIndex:4] intValue];
  403. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  404. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  405. dateComp.hour = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
  406. dateComp.minute = [[dateString substringWithRange:NSMakeRange(10, 2)] intValue];
  407. dateComp.second = [[dateString substringWithRange:NSMakeRange(12, 2)] intValue];
  408. } else if ([dateString rangeOfString:@"-"].location != NSNotFound) {
  409. NSArray *dateArray = [dateString componentsSeparatedByString:@"-"];
  410. if (dateArray && dateArray.count > 0) {
  411. dateComp = [[NSDateComponents alloc] init];
  412. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  413. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  414. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  415. }
  416. } else if ([dateString rangeOfString:@"/"].location != NSNotFound) {
  417. NSArray *dateArray = [dateString componentsSeparatedByString:@"/"];
  418. if (dateArray && dateArray.count > 0) {
  419. dateComp = [[NSDateComponents alloc] init];
  420. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  421. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  422. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  423. }
  424. } else if ([dateString rangeOfString:@"."].location != NSNotFound) {
  425. NSArray *dateArray = [dateString componentsSeparatedByString:@"."];
  426. if (dateArray && dateArray.count > 0) {
  427. dateComp = [[NSDateComponents alloc] init];
  428. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  429. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  430. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  431. }
  432. }
  433. return dateComp;
  434. }
  435. + (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
  436. NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
  437. [df_local setTimeZone:[NSTimeZone systemTimeZone]];
  438. [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
  439. NSDate *locTime = [df_local dateFromString:utcString];
  440. return [CommonUtil dateComponents:locTime];
  441. }
  442. + (NSDate *)dateFromDateString:(NSString *)dateString {
  443. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  444. NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
  445. return newDate;
  446. }
  447. + (NSString *)stringFromDateComponents:(NSDateComponents *)components {
  448. NSMutableString *rString = [NSMutableString new];
  449. if (components.year > 0) {
  450. [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
  451. }
  452. if (components.month > 0) {
  453. if (rString.length > 0) {
  454. [rString appendString:@" "];
  455. }
  456. [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
  457. }
  458. if (components.day > 0) {
  459. if (rString.length > 0) {
  460. [rString appendString:@" "];
  461. }
  462. [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
  463. }
  464. return rString;
  465. }
  466. + (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
  467. NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
  468. NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
  469. NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
  470. return rString;
  471. }
  472. + (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
  473. NSMutableString *rString = [NSMutableString new];
  474. if (components.year > 0) {
  475. [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
  476. }
  477. if (components.month > 0) {
  478. if (components.month < 10) {
  479. [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
  480. } else {
  481. [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
  482. }
  483. }
  484. return rString;
  485. }
  486. + (NSString *)paramMonthFromDateString:(NSString *)dateString {
  487. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  488. ds.day = 1;
  489. NSDateFormatter *df = [CommonUtil dateFormatter];
  490. df.dateFormat = @"YYYYMM";
  491. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  492. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  493. }
  494. + (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
  495. NSDateComponents *ds = [CommonUtil dateComponents:date];
  496. ds.day += day;
  497. NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
  498. return adjustDate;
  499. }
  500. //현재 로컬시간을 UTC로 변환합니다.
  501. + (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
  502. NSDateFormatter *df = [CommonUtil dateFormatter];
  503. [df setDateFormat:@"yyyyMMddHHmmss"];
  504. NSDate *locDate = [df dateFromString:locDateString];
  505. NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
  506. dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
  507. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  508. [dfu setTimeZone:utc];
  509. NSString *timeStamp = [dfu stringFromDate:locDate];
  510. timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
  511. return timeStamp;
  512. }
  513. //UTC 시간을 현재 로컬 시간을 변환합니다.
  514. + (NSString *)localDateFromUTC:(NSString *)utcDateString {
  515. NSDateFormatter *df = [CommonUtil dateFormatter];
  516. [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
  517. NSDate *utcDate = [df dateFromString:utcDateString];
  518. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  519. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  520. [dfl setDateFormat:@"yyyyMMddHHmmss"];
  521. NSString* localString = [dfl stringFromDate:utcDate];
  522. return localString;
  523. }
  524. + (NSString *)localDateFromUTC2:(NSString *)utcDateString {
  525. NSDateFormatter *df = [[CommonUtil dateFormatter] copy];
  526. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  527. [df setTimeZone:utc];
  528. [df setDateFormat:@"yyyyMMddHHmmss"];
  529. NSDate *utcDate = [df dateFromString:utcDateString];
  530. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  531. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  532. [dfl setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  533. NSString* localString = [dfl stringFromDate:utcDate];
  534. return localString;
  535. }
  536. + (NSString *)formattedDate:(NSString *)dateString {
  537. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  538. NSDateFormatter *df = [CommonUtil dateFormatter];
  539. df.dateFormat = @"YYYY년 M월 d일";
  540. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  541. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  542. }
  543. + (NSString *)formattedDate2:(NSString *)dateString {
  544. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  545. NSDateFormatter *df = [CommonUtil dateFormatter];
  546. df.dateFormat = @"YYYY.MM.dd";
  547. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  548. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  549. }
  550. //기본 날짜포맷을 반환
  551. + (NSString *)formattedDate3:(NSString *)datetime {
  552. NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
  553. NSDateFormatter *df = [CommonUtil dateFormatter];
  554. df.dateFormat = @"YYYY년 MM월 dd일";
  555. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  556. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  557. }
  558. + (NSString *)formattedMonthDate:(NSString *)dateString {
  559. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  560. NSDateFormatter *df = [CommonUtil dateFormatter];
  561. df.dateFormat = @"YYYY.MM";
  562. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  563. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  564. }
  565. #pragma mark - TimeUtil
  566. + (NSString *)formattedTime:(NSString *)timeString {
  567. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  568. NSDateFormatter *df = [CommonUtil dateFormatter];
  569. df.dateFormat = @"HH시 mm분";
  570. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  571. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  572. }
  573. + (NSString *)formattedTime2:(NSString *)timeString {
  574. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  575. NSDateFormatter *df = [CommonUtil dateFormatter];
  576. df.dateFormat = @"HH시 mm분";
  577. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  578. if ([period isEqualToString:@"오후"]) {
  579. ds.hour -= 12;
  580. }
  581. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  582. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  583. }
  584. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  585. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  586. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  587. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  588. NSString *hour = [timeArray firstObject];
  589. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  590. NSString *minute = [timeArray lastObject];
  591. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  592. dateComp.hour = [hour intValue];
  593. dateComp.minute = [minute intValue];
  594. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  595. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  596. if (timeArray && timeArray.count > 0) {
  597. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  598. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  599. }
  600. }
  601. return dateComp;
  602. }
  603. + (NSString *)stringFromTime:(NSDate *)date {
  604. NSDateFormatter *df = [CommonUtil dateFormatter];
  605. df.dateFormat = @"HH:mm";
  606. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  607. }
  608. #pragma mark - StringUtil
  609. + (NSNumberFormatter *)numberFormatter {
  610. static NSNumberFormatter *__shareNumberFormatter = nil;
  611. static dispatch_once_t onceToken;
  612. dispatch_once(&onceToken, ^{
  613. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  614. NSLocale *locale = [NSLocale currentLocale];
  615. [__shareNumberFormatter setLocale:locale];
  616. });
  617. return __shareNumberFormatter;
  618. }
  619. + (NSString *)numberString:(NSInteger)number {
  620. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  621. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  622. formatter.usesGroupingSeparator = YES;
  623. [formatter setGroupingSeparator:@","];
  624. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  625. return formattedString;
  626. }
  627. + (NSString *)currencyString:(NSInteger)number {
  628. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  629. if (number <= 0) {
  630. return currency;
  631. }
  632. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  633. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  634. formatter.usesGroupingSeparator = YES;
  635. [formatter setGroupingSeparator:@","];
  636. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  637. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  638. return currency;
  639. }
  640. + (NSString *)currencyString2:(NSInteger)number {
  641. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  642. if (number <= 0) {
  643. return currency;
  644. }
  645. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  646. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  647. formatter.usesGroupingSeparator = YES;
  648. [formatter setGroupingSeparator:@","];
  649. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  650. currency = [NSString stringWithFormat:@"%@원", formattedString];
  651. return currency;
  652. }
  653. + (NSString *)svcNoString:(NSString *)svcNo {
  654. //0103333333
  655. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  656. if (svcNo.length == 10) {
  657. [tmpSvcNo insertString:@"-" atIndex:3];
  658. [tmpSvcNo insertString:@"-" atIndex:7];
  659. } else if (svcNo.length == 11) {
  660. [tmpSvcNo insertString:@"-" atIndex:3];
  661. [tmpSvcNo insertString:@"-" atIndex:8];
  662. }
  663. return tmpSvcNo;
  664. }
  665. + (NSString *)cutSaName:(NSString *)saName {
  666. NSRange range = [saName rangeOfString:@"]"];
  667. NSString *rSaName = nil;
  668. if (range.location != NSNotFound) {
  669. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  670. }
  671. return rSaName;
  672. }
  673. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  674. NSInteger rvalue = 0;
  675. NSString *tmp = [NSString stringWithString:currency];
  676. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  677. if (fRange.location == currency.length-1) {
  678. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  679. }
  680. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  681. rvalue = [tmp intValue];
  682. return rvalue;
  683. }
  684. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  685. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  686. return phoneNumber;
  687. }
  688. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  689. NSInteger lastIndex = phoneNumber.length - 3;
  690. [rString insertString:@"-" atIndex:3];
  691. [rString insertString:@"-" atIndex:lastIndex];
  692. return rString;
  693. }
  694. + (NSString *)formattedIAId:(NSString *)iaId {
  695. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  696. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  697. return formatIAId;
  698. }
  699. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  700. NSInteger count = 0, length = [occurString length];
  701. NSRange range = NSMakeRange(0, length);
  702. while(range.location != NSNotFound) {
  703. range = [occurString rangeOfString:occurString options:0 range:range];
  704. if(range.location != NSNotFound) {
  705. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  706. count++;
  707. }
  708. }
  709. return count;
  710. }
  711. +(NSString *)URLEncoding:(NSString *)sender{
  712. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  713. NULL,
  714. (CFStringRef)sender,
  715. NULL,
  716. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  717. kCFStringEncodingUTF8 ));
  718. return encodedString;
  719. }
  720. +(NSString *)URLDecoding:(NSString *)sender {
  721. // Decode a percent escape encoded string.
  722. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  723. (CFStringRef) sender,
  724. CFSTR(""),
  725. kCFStringEncodingUTF8));
  726. return decodeString;
  727. }
  728. #pragma getUrlPostUrl
  729. + (NSString *)switchPostUrl:(NSString *)getUrl{
  730. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  731. NSString *splturl = [urlLst objectAtIndex:1];
  732. return splturl;
  733. }
  734. + (NSString *)getUrl:(NSString *)getUrl{
  735. NSString *url;
  736. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  737. url = [urlLst objectAtIndex:0];
  738. return url;
  739. }
  740. + (BOOL)stringContainsEmoji:(NSString *)string {
  741. __block BOOL returnValue = NO;
  742. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  743. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  744. const unichar hs = [substring characterAtIndex:0];
  745. // surrogate pair
  746. if (0xd800 <= hs && hs <= 0xdbff) {
  747. if (substring.length > 1) {
  748. const unichar ls = [substring characterAtIndex:1];
  749. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  750. if (0x1d000 <= uc && uc <= 0x1f77f) {
  751. returnValue = YES;
  752. }
  753. }
  754. } else if (substring.length > 1) {
  755. const unichar ls = [substring characterAtIndex:1];
  756. if (ls == 0x20e3) {
  757. returnValue = YES;
  758. }
  759. } else {
  760. // non surrogate
  761. if (0x2100 <= hs && hs <= 0x27ff) {
  762. returnValue = YES;
  763. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  764. returnValue = YES;
  765. } else if (0x2934 <= hs && hs <= 0x2935) {
  766. returnValue = YES;
  767. } else if (0x3297 <= hs && hs <= 0x3299) {
  768. returnValue = YES;
  769. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  770. returnValue = YES;
  771. }
  772. }
  773. }];
  774. return returnValue;
  775. }
  776. #pragma mark - TimeZone Dictionary
  777. + (SortDictionary *)timeZoneDict {
  778. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  779. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  780. return [[SortDictionary alloc] initWithDictionary:dic];
  781. }
  782. #pragma mark - Color
  783. +(UIColor *)convertFromRGBToUIColor:(NSString *)hexRGB {
  784. NSString *cleanString = [hexRGB stringByReplacingOccurrencesOfString:@"#" withString:@""];
  785. if ([cleanString length] == 3) {
  786. cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", [cleanString substringWithRange:NSMakeRange(0, 1)], [cleanString substringWithRange:NSMakeRange(0, 1)],
  787. [cleanString substringWithRange:NSMakeRange(1, 1)], [cleanString substringWithRange:NSMakeRange(1, 1)],
  788. [cleanString substringWithRange:NSMakeRange(2, 1)], [cleanString substringWithRange:NSMakeRange(2, 1)]];
  789. }
  790. if ([cleanString length] == 6) {
  791. cleanString = [cleanString stringByAppendingString:@"ff"];
  792. }
  793. unsigned int baseValue;
  794. [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
  795. float red = ((baseValue >> 24) & 0xFF) / 255.0f;
  796. float green = ((baseValue >> 16) & 0xFF) / 255.0f;
  797. float blue = ((baseValue >> 8) & 0xFF) / 255.0f;
  798. float alpha = ((baseValue >> 0) & 0xFF) / 255.0f;
  799. return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
  800. }
  801. @end