CommonUtil.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. vc = vc.presentedViewController;
  154. if ([vc isKindOfClass:[UINavigationController class]]) {
  155. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  156. vc = [vcArray objectAtIndex:vcArray.count - 1];
  157. }
  158. return vc;
  159. }
  160. if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
  161. vc = vc.presentingViewController;
  162. }
  163. if ([NSClassFromString(@"ECSlidingViewController") class] && [vc isKindOfClass:[NSClassFromString(@"ECSlidingViewController") class]]) {
  164. id slideController = vc;
  165. vc = (UINavigationController *)[slideController topViewController];
  166. }
  167. if ([vc isKindOfClass:[UINavigationController class]]) {
  168. NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
  169. vc = [vcArray objectAtIndex:vcArray.count - 1];
  170. }
  171. return vc;
  172. }
  173. + (UIView *)topView
  174. {
  175. UIView *topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
  176. if ([topView isKindOfClass:NSClassFromString(@"UITransitionView")]) {
  177. topView = [[topView subviews] lastObject];
  178. }
  179. if ([topView isKindOfClass:NSClassFromString(@"CustomLoadingView")]) {
  180. topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
  181. topView = [topView subviews][topView.subviews.count - 2];
  182. }
  183. topView = topView == nil ? [[UIApplication sharedApplication] keyWindow] : topView;
  184. return topView;
  185. }
  186. + (CGRect)mainScreenBounds {
  187. CGRect screenRect = [UIScreen mainScreen].bounds;
  188. return screenRect;
  189. }
  190. //해당 컨테이너로부터 해당 객체의 중앙 지점을 연산하여 반환함.
  191. + (CGRect)getCenterPosition:(id)object fromContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
  192. CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
  193. if (object && container) {
  194. CGRect cframe = [container frame];
  195. CGRect oframe = [object frame];
  196. float nHeight = hasNavigationBar ? 44.0 : 0;
  197. float tHeight = hasTabBar ? 59.0 : 0;
  198. float x = ((cframe.size.width - oframe.size.width) / 2);
  199. float y = (cframe.size.height - (oframe.size.height - nHeight - tHeight)) / 2;
  200. frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
  201. }
  202. return frame;
  203. }
  204. + (CGRect)centerRect:(id)object fromContainer:(id)container {
  205. CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
  206. if (object && container) {
  207. CGRect cframe = [container frame];
  208. CGRect oframe = [object frame];
  209. float x = ((cframe.size.width - oframe.size.width) / 2);
  210. float y = (cframe.size.height - (oframe.size.height)) / 2;
  211. frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
  212. }
  213. return frame;
  214. }
  215. //해당 객체를 해당 컨테이너의 중앙(가로*세로)에 위치시킴.
  216. + (void)moveToCenter:(id)object withContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
  217. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:hasNavigationBar hasTabBar:hasTabBar];
  218. UIView *oView = (UIView *)object;
  219. [oView setFrame:rect];
  220. }
  221. //해당 객체를 해당 컨테이너의 중앙(가로)에 위치시킴.
  222. + (void)moveToCenterHorizon:(id)object withContainer:(id)container {
  223. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
  224. CGRect oframe = [object frame];
  225. oframe.origin.x = rect.origin.x;
  226. UIView *oView = (UIView *)object;
  227. [oView setFrame:oframe];
  228. }
  229. //해당 객체를 해당 컨테이너의 중앙(세로)에 위치시킴.
  230. + (void)moveToCenterVertical:(id)object withContainer:(id)container {
  231. CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
  232. CGRect oframe = [object frame];
  233. oframe.origin.y = rect.origin.y;
  234. UIView *oView = (UIView *)object;
  235. [oView setFrame:oframe];
  236. }
  237. + (CGSize)sizeWithString:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)constrainedToSize lineBreakMode:(NSLineBreakMode)lineBreakMode {
  238. CGSize size = CGSizeZero;
  239. if (IOS_VERSION >= 7.0f) {
  240. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  241. CGRect rect = [attributedText boundingRectWithSize:(CGSize){constrainedToSize.width, CGFLOAT_MAX}
  242. options:NSStringDrawingUsesLineFragmentOrigin
  243. context:nil];
  244. size = rect.size;
  245. }
  246. return size;
  247. }
  248. + (float)sizeWithStringHeight:(NSString *)text font:(UIFont *)font constrainedToSize:(float)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
  249. float size = 0;
  250. if (IOS_VERSION >= 7.0f) {
  251. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  252. CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
  253. options:NSStringDrawingUsesLineFragmentOrigin
  254. context:nil];
  255. size = rect.size.height;
  256. }
  257. return size;
  258. }
  259. + (CGFloat)getLabelRealWidth:(UILabel *)label fixedWidth:(CGFloat)fixedWidth {
  260. CGFloat width = 0.0f;
  261. CGRect oriRect = label.frame;
  262. CGRect chRect = label.frame;
  263. chRect.size.width = fixedWidth;
  264. label.frame = chRect;
  265. [label sizeToFit];
  266. width = label.frame.size.width;
  267. label.frame = oriRect;
  268. return width;
  269. }
  270. + (CGFloat)getLabelRealHeight:(UILabel *)label {
  271. CGFloat height = 0.0f;
  272. CGRect oriRect = label.frame;
  273. [label sizeToFit];
  274. height = label.frame.size.height;
  275. label.frame = oriRect;
  276. return height;
  277. }
  278. + (CGSize)getLabelRealSize:(UILabel *)label fixedWdith:(CGFloat)fixedWidth {
  279. CGFloat width = [CommonUtil getLabelRealWidth:label fixedWidth:fixedWidth];
  280. CGFloat height = [CommonUtil getLabelRealHeight:label];
  281. return CGSizeMake(width, height);
  282. }
  283. + (CGSize)getSizeFromString:(NSString *)string font:(UIFont *)font width:(CGFloat)fixedWidth {
  284. if ([string isEqualToString:ksEmptyString]) {
  285. return CGSizeZero;
  286. }
  287. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  288. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  289. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:context];
  290. r = CGRectIntegral(r);
  291. return r.size;
  292. }
  293. + (CGSize)getSizeFromAttributeString:(NSAttributedString *)string width:(CGFloat)fixedWidth {
  294. if ([string.string isEqualToString:ksEmptyString]) {
  295. return CGSizeZero;
  296. }
  297. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  298. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  299. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin context:context];
  300. r = CGRectIntegral(r);
  301. return r.size;
  302. }
  303. /**
  304. NIB에서 해당 뷰를 로드함.
  305. @return NSArray * 뷰어레이
  306. */
  307. + (NSArray *)nibViews:(NSString *)nibName {
  308. UINib *nib = [UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]];
  309. return [nib instantiateWithOwner:nil options:nil];
  310. }
  311. #pragma mark - Date Util
  312. + (NSCalendar *)calendar {
  313. NSCalendar *cal = [NSCalendar currentCalendar];
  314. [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
  315. return cal;
  316. }
  317. + (NSDateFormatter *)dateFormatter {
  318. static NSDateFormatter *__shareDateFormatter = nil;
  319. static dispatch_once_t onceToken;
  320. dispatch_once(&onceToken, ^{
  321. __shareDateFormatter = [[NSDateFormatter alloc] init];
  322. NSLocale *locale = [NSLocale currentLocale];
  323. [__shareDateFormatter setLocale:locale];
  324. });
  325. return __shareDateFormatter;
  326. }
  327. + (NSString *)currentMonth {
  328. NSDateFormatter *df = [CommonUtil dateFormatter];
  329. df.dateFormat = @"YYYY.MM";
  330. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  331. return title;
  332. }
  333. + (NSDateComponents *)dateComponents:(NSDate *)date {
  334. NSCalendar *calendar = [CommonUtil calendar];
  335. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  336. NSCalendarUnitMonth |
  337. NSCalendarUnitDay |
  338. NSCalendarUnitHour |
  339. NSCalendarUnitMinute|
  340. NSCalendarUnitSecond|
  341. NSCalendarUnitTimeZone) fromDate:date];
  342. return components;
  343. }
  344. + (NSDateComponents *)dateComponents:(NSDate *)date timezone:(NSTimeZone *)timezone {
  345. NSCalendar *calendar = [CommonUtil calendar];
  346. [calendar setTimeZone:timezone];
  347. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  348. NSCalendarUnitMonth |
  349. NSCalendarUnitDay |
  350. NSCalendarUnitHour |
  351. NSCalendarUnitMinute|
  352. NSCalendarUnitSecond|
  353. NSCalendarUnitTimeZone) fromDate:date];
  354. return components;
  355. }
  356. //Date객체를 String객체로 전환
  357. + (NSString *)stringFromDate:(NSDate *)date {
  358. NSDateFormatter *df = [CommonUtil dateFormatter];
  359. df.dateFormat = @"YYYY/MM/dd";
  360. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  361. }
  362. + (NSString *)stringFromDateTime:(NSDate *)date {
  363. NSDateFormatter *df = [CommonUtil dateFormatter];
  364. df.dateFormat = @"yyyyMMddHHmmss";
  365. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  366. }
  367. + (NSString *)birthStringFromDate:(NSDate *)date {
  368. NSDateFormatter *df = [CommonUtil dateFormatter];
  369. df.dateFormat = @"YYYYMMdd";
  370. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  371. }
  372. + (NSString *)stringFromDate2:(NSDate *)date {
  373. NSDateFormatter *df = [CommonUtil dateFormatter];
  374. df.dateFormat = @"YYYY-MM-dd";
  375. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  376. }
  377. + (NSString *)stringFromString:(NSString *)dateString {
  378. NSDateComponents *components = [CommonUtil dateComponentsFromString:dateString];
  379. return [CommonUtil stringFromDateComponents:components];
  380. }
  381. + (NSDateComponents *)dateComponentsFromString:(NSString *)dateString {
  382. NSDateComponents *dateComp = nil;
  383. if (dateString && dateString.length == 6) {//19990101 타입
  384. dateComp = [[NSDateComponents alloc] init];
  385. dateComp.year = [[dateString substringToIndex:4] intValue];
  386. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  387. } else if (dateString && dateString.length == 8) {//19990101 타입
  388. dateComp = [[NSDateComponents alloc] init];
  389. dateComp.year = [[dateString substringToIndex:4] intValue];
  390. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  391. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  392. } else if ([dateString rangeOfString:@"-"].location != NSNotFound) {
  393. NSArray *dateArray = [dateString componentsSeparatedByString:@"-"];
  394. if (dateArray && dateArray.count > 0) {
  395. dateComp = [[NSDateComponents alloc] init];
  396. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  397. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  398. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  399. }
  400. } else if ([dateString rangeOfString:@"/"].location != NSNotFound) {
  401. NSArray *dateArray = [dateString componentsSeparatedByString:@"/"];
  402. if (dateArray && dateArray.count > 0) {
  403. dateComp = [[NSDateComponents alloc] init];
  404. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  405. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  406. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  407. }
  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. }
  417. return dateComp;
  418. }
  419. + (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
  420. NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
  421. [df_local setTimeZone:[NSTimeZone systemTimeZone]];
  422. [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
  423. NSDate *locTime = [df_local dateFromString:utcString];
  424. return [CommonUtil dateComponents:locTime];
  425. }
  426. + (NSDate *)dateFromDateString:(NSString *)dateString {
  427. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  428. NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
  429. return newDate;
  430. }
  431. + (NSString *)stringFromDateComponents:(NSDateComponents *)components {
  432. NSMutableString *rString = [NSMutableString new];
  433. if (components.year > 0) {
  434. [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
  435. }
  436. if (components.month > 0) {
  437. if (rString.length > 0) {
  438. [rString appendString:@" "];
  439. }
  440. [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
  441. }
  442. if (components.day > 0) {
  443. if (rString.length > 0) {
  444. [rString appendString:@" "];
  445. }
  446. [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
  447. }
  448. return rString;
  449. }
  450. + (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
  451. NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
  452. NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
  453. NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
  454. return rString;
  455. }
  456. + (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
  457. NSMutableString *rString = [NSMutableString new];
  458. if (components.year > 0) {
  459. [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
  460. }
  461. if (components.month > 0) {
  462. if (components.month < 10) {
  463. [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
  464. } else {
  465. [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
  466. }
  467. }
  468. return rString;
  469. }
  470. + (NSString *)paramMonthFromDateString:(NSString *)dateString {
  471. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  472. ds.day = 1;
  473. NSDateFormatter *df = [CommonUtil dateFormatter];
  474. df.dateFormat = @"YYYYMM";
  475. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  476. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  477. }
  478. + (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
  479. NSDateComponents *ds = [CommonUtil dateComponents:date];
  480. ds.day += day;
  481. NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
  482. return adjustDate;
  483. }
  484. //현재 로컬시간을 UTC로 변환합니다.
  485. + (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
  486. NSDateFormatter *df = [CommonUtil dateFormatter];
  487. [df setDateFormat:@"yyyyMMddHHmmss"];
  488. NSDate *locDate = [df dateFromString:locDateString];
  489. NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
  490. dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
  491. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  492. [dfu setTimeZone:utc];
  493. NSString *timeStamp = [dfu stringFromDate:locDate];
  494. timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
  495. return timeStamp;
  496. }
  497. //UTC 시간을 현재 로컬 시간을 변환합니다.
  498. + (NSString *)localDateFromUTC:(NSString *)utcDateString {
  499. NSDateFormatter *df = [CommonUtil dateFormatter];
  500. [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
  501. NSDate *utcDate = [df dateFromString:utcDateString];
  502. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  503. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  504. [dfl setDateFormat:@"yyyyMMddHHmmss"];
  505. NSString* localString = [dfl stringFromDate:utcDate];
  506. return localString;
  507. }
  508. #pragma mark - TimeUtil
  509. + (NSString *)formattedTime:(NSString *)timeString {
  510. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  511. NSDateFormatter *df = [CommonUtil dateFormatter];
  512. df.dateFormat = @"HH시 mm분";
  513. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  514. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  515. }
  516. + (NSString *)formattedTime2:(NSString *)timeString {
  517. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  518. NSDateFormatter *df = [CommonUtil dateFormatter];
  519. df.dateFormat = @"HH시 mm분";
  520. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  521. if ([period isEqualToString:@"오후"]) {
  522. ds.hour -= 12;
  523. }
  524. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  525. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  526. }
  527. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  528. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  529. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  530. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  531. NSString *hour = [timeArray firstObject];
  532. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  533. NSString *minute = [timeArray lastObject];
  534. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  535. dateComp.hour = [hour intValue];
  536. dateComp.minute = [minute intValue];
  537. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  538. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  539. if (timeArray && timeArray.count > 0) {
  540. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  541. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  542. }
  543. }
  544. return dateComp;
  545. }
  546. + (NSString *)stringFromTime:(NSDate *)date {
  547. NSDateFormatter *df = [CommonUtil dateFormatter];
  548. df.dateFormat = @"HH:mm";
  549. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  550. }
  551. #pragma mark - StringUtil
  552. + (NSNumberFormatter *)numberFormatter {
  553. static NSNumberFormatter *__shareNumberFormatter = nil;
  554. static dispatch_once_t onceToken;
  555. dispatch_once(&onceToken, ^{
  556. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  557. NSLocale *locale = [NSLocale currentLocale];
  558. [__shareNumberFormatter setLocale:locale];
  559. });
  560. return __shareNumberFormatter;
  561. }
  562. + (NSString *)numberString:(NSInteger)number {
  563. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  564. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  565. formatter.usesGroupingSeparator = YES;
  566. [formatter setGroupingSeparator:@","];
  567. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  568. return formattedString;
  569. }
  570. + (NSString *)currencyString:(NSInteger)number {
  571. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  572. if (number <= 0) {
  573. return currency;
  574. }
  575. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  576. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  577. formatter.usesGroupingSeparator = YES;
  578. [formatter setGroupingSeparator:@","];
  579. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  580. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  581. return currency;
  582. }
  583. + (NSString *)currencyString2:(NSInteger)number {
  584. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  585. if (number <= 0) {
  586. return currency;
  587. }
  588. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  589. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  590. formatter.usesGroupingSeparator = YES;
  591. [formatter setGroupingSeparator:@","];
  592. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  593. currency = [NSString stringWithFormat:@"%@원", formattedString];
  594. return currency;
  595. }
  596. + (NSString *)svcNoString:(NSString *)svcNo {
  597. //0103333333
  598. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  599. if (svcNo.length == 10) {
  600. [tmpSvcNo insertString:@"-" atIndex:3];
  601. [tmpSvcNo insertString:@"-" atIndex:7];
  602. } else if (svcNo.length == 11) {
  603. [tmpSvcNo insertString:@"-" atIndex:3];
  604. [tmpSvcNo insertString:@"-" atIndex:8];
  605. }
  606. return tmpSvcNo;
  607. }
  608. + (NSString *)cutSaName:(NSString *)saName {
  609. NSRange range = [saName rangeOfString:@"]"];
  610. NSString *rSaName = nil;
  611. if (range.location != NSNotFound) {
  612. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  613. }
  614. return rSaName;
  615. }
  616. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  617. NSInteger rvalue = 0;
  618. NSString *tmp = [NSString stringWithString:currency];
  619. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  620. if (fRange.location == currency.length-1) {
  621. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  622. }
  623. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  624. rvalue = [tmp intValue];
  625. return rvalue;
  626. }
  627. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  628. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  629. return phoneNumber;
  630. }
  631. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  632. NSInteger lastIndex = phoneNumber.length - 3;
  633. [rString insertString:@"-" atIndex:3];
  634. [rString insertString:@"-" atIndex:lastIndex];
  635. return rString;
  636. }
  637. + (NSString *)formattedDate:(NSString *)dateString {
  638. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  639. NSDateFormatter *df = [CommonUtil dateFormatter];
  640. df.dateFormat = @"YYYY/MM/dd";
  641. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  642. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  643. }
  644. + (NSString *)formattedDate2:(NSString *)dateString {
  645. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  646. NSDateFormatter *df = [CommonUtil dateFormatter];
  647. df.dateFormat = @"YYYY.MM.dd";
  648. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  649. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  650. }
  651. + (NSString *)formattedMonthDate:(NSString *)dateString {
  652. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  653. NSDateFormatter *df = [CommonUtil dateFormatter];
  654. df.dateFormat = @"YYYY.MM";
  655. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  656. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  657. }
  658. + (NSString *)formattedIAId:(NSString *)iaId {
  659. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  660. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  661. return formatIAId;
  662. }
  663. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  664. NSInteger count = 0, length = [occurString length];
  665. NSRange range = NSMakeRange(0, length);
  666. while(range.location != NSNotFound) {
  667. range = [occurString rangeOfString:occurString options:0 range:range];
  668. if(range.location != NSNotFound) {
  669. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  670. count++;
  671. }
  672. }
  673. return count;
  674. }
  675. +(NSString *)URLEncoding:(NSString *)sender{
  676. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  677. NULL,
  678. (CFStringRef)sender,
  679. NULL,
  680. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  681. kCFStringEncodingUTF8 ));
  682. return encodedString;
  683. }
  684. +(NSString *)URLDecoding:(NSString *)sender {
  685. // Decode a percent escape encoded string.
  686. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  687. (CFStringRef) sender,
  688. CFSTR(""),
  689. kCFStringEncodingUTF8));
  690. return decodeString;
  691. }
  692. #pragma getUrlPostUrl
  693. + (NSString *)switchPostUrl:(NSString *)getUrl{
  694. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  695. NSString *splturl = [urlLst objectAtIndex:1];
  696. return splturl;
  697. }
  698. + (NSString *)getUrl:(NSString *)getUrl{
  699. NSString *url;
  700. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  701. url = [urlLst objectAtIndex:0];
  702. return url;
  703. }
  704. + (BOOL)stringContainsEmoji:(NSString *)string {
  705. __block BOOL returnValue = NO;
  706. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  707. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  708. const unichar hs = [substring characterAtIndex:0];
  709. // surrogate pair
  710. if (0xd800 <= hs && hs <= 0xdbff) {
  711. if (substring.length > 1) {
  712. const unichar ls = [substring characterAtIndex:1];
  713. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  714. if (0x1d000 <= uc && uc <= 0x1f77f) {
  715. returnValue = YES;
  716. }
  717. }
  718. } else if (substring.length > 1) {
  719. const unichar ls = [substring characterAtIndex:1];
  720. if (ls == 0x20e3) {
  721. returnValue = YES;
  722. }
  723. } else {
  724. // non surrogate
  725. if (0x2100 <= hs && hs <= 0x27ff) {
  726. returnValue = YES;
  727. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  728. returnValue = YES;
  729. } else if (0x2934 <= hs && hs <= 0x2935) {
  730. returnValue = YES;
  731. } else if (0x3297 <= hs && hs <= 0x3299) {
  732. returnValue = YES;
  733. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  734. returnValue = YES;
  735. }
  736. }
  737. }];
  738. return returnValue;
  739. }
  740. #pragma mark - TimeZone Dictionary
  741. + (SortDictionary *)timeZoneDict {
  742. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  743. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  744. return [[SortDictionary alloc] initWithDictionary:dic];
  745. }
  746. @end