CommonUtil.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. while ([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 && dateString.length == 14) {//19990101010101 타입
  393. dateComp = [[NSDateComponents alloc] init];
  394. dateComp.year = [[dateString substringToIndex:4] intValue];
  395. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  396. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  397. dateComp.hour = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
  398. dateComp.minute = [[dateString substringWithRange:NSMakeRange(10, 2)] intValue];
  399. dateComp.second = [[dateString substringWithRange:NSMakeRange(12, 2)] intValue];
  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. } 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. }
  425. return dateComp;
  426. }
  427. + (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
  428. NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
  429. [df_local setTimeZone:[NSTimeZone systemTimeZone]];
  430. [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
  431. NSDate *locTime = [df_local dateFromString:utcString];
  432. return [CommonUtil dateComponents:locTime];
  433. }
  434. + (NSDate *)dateFromDateString:(NSString *)dateString {
  435. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  436. NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
  437. return newDate;
  438. }
  439. + (NSString *)stringFromDateComponents:(NSDateComponents *)components {
  440. NSMutableString *rString = [NSMutableString new];
  441. if (components.year > 0) {
  442. [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
  443. }
  444. if (components.month > 0) {
  445. if (rString.length > 0) {
  446. [rString appendString:@" "];
  447. }
  448. [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
  449. }
  450. if (components.day > 0) {
  451. if (rString.length > 0) {
  452. [rString appendString:@" "];
  453. }
  454. [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
  455. }
  456. return rString;
  457. }
  458. + (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
  459. NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
  460. NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
  461. NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
  462. return rString;
  463. }
  464. + (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
  465. NSMutableString *rString = [NSMutableString new];
  466. if (components.year > 0) {
  467. [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
  468. }
  469. if (components.month > 0) {
  470. if (components.month < 10) {
  471. [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
  472. } else {
  473. [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
  474. }
  475. }
  476. return rString;
  477. }
  478. + (NSString *)paramMonthFromDateString:(NSString *)dateString {
  479. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  480. ds.day = 1;
  481. NSDateFormatter *df = [CommonUtil dateFormatter];
  482. df.dateFormat = @"YYYYMM";
  483. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  484. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  485. }
  486. + (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
  487. NSDateComponents *ds = [CommonUtil dateComponents:date];
  488. ds.day += day;
  489. NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
  490. return adjustDate;
  491. }
  492. //현재 로컬시간을 UTC로 변환합니다.
  493. + (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
  494. NSDateFormatter *df = [CommonUtil dateFormatter];
  495. [df setDateFormat:@"yyyyMMddHHmmss"];
  496. NSDate *locDate = [df dateFromString:locDateString];
  497. NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
  498. dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
  499. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  500. [dfu setTimeZone:utc];
  501. NSString *timeStamp = [dfu stringFromDate:locDate];
  502. timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
  503. return timeStamp;
  504. }
  505. //UTC 시간을 현재 로컬 시간을 변환합니다.
  506. + (NSString *)localDateFromUTC:(NSString *)utcDateString {
  507. NSDateFormatter *df = [CommonUtil dateFormatter];
  508. [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
  509. NSDate *utcDate = [df dateFromString:utcDateString];
  510. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  511. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  512. [dfl setDateFormat:@"yyyyMMddHHmmss"];
  513. NSString* localString = [dfl stringFromDate:utcDate];
  514. return localString;
  515. }
  516. + (NSString *)localDateFromUTC2:(NSString *)utcDateString {
  517. NSDateFormatter *df = [[CommonUtil dateFormatter] copy];
  518. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  519. [df setTimeZone:utc];
  520. [df setDateFormat:@"yyyyMMddHHmmss"];
  521. NSDate *utcDate = [df dateFromString:utcDateString];
  522. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  523. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  524. [dfl setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  525. NSString* localString = [dfl stringFromDate:utcDate];
  526. return localString;
  527. }
  528. + (NSString *)formattedDate:(NSString *)dateString {
  529. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  530. NSDateFormatter *df = [CommonUtil dateFormatter];
  531. df.dateFormat = @"YYYY/MM/dd";
  532. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  533. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  534. }
  535. + (NSString *)formattedDate2:(NSString *)dateString {
  536. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  537. NSDateFormatter *df = [CommonUtil dateFormatter];
  538. df.dateFormat = @"YYYY.MM.dd";
  539. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  540. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  541. }
  542. //기본 날짜포맷을 반환
  543. + (NSString *)formattedDate3:(NSString *)datetime {
  544. NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
  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. + (NSString *)formattedMonthDate:(NSString *)dateString {
  551. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  552. NSDateFormatter *df = [CommonUtil dateFormatter];
  553. df.dateFormat = @"YYYY.MM";
  554. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  555. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  556. }
  557. #pragma mark - TimeUtil
  558. + (NSString *)formattedTime:(NSString *)timeString {
  559. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  560. NSDateFormatter *df = [CommonUtil dateFormatter];
  561. df.dateFormat = @"HH시 mm분";
  562. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  563. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  564. }
  565. + (NSString *)formattedTime2:(NSString *)timeString {
  566. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  567. NSDateFormatter *df = [CommonUtil dateFormatter];
  568. df.dateFormat = @"HH시 mm분";
  569. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  570. if ([period isEqualToString:@"오후"]) {
  571. ds.hour -= 12;
  572. }
  573. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  574. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  575. }
  576. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  577. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  578. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  579. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  580. NSString *hour = [timeArray firstObject];
  581. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  582. NSString *minute = [timeArray lastObject];
  583. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  584. dateComp.hour = [hour intValue];
  585. dateComp.minute = [minute intValue];
  586. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  587. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  588. if (timeArray && timeArray.count > 0) {
  589. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  590. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  591. }
  592. }
  593. return dateComp;
  594. }
  595. + (NSString *)stringFromTime:(NSDate *)date {
  596. NSDateFormatter *df = [CommonUtil dateFormatter];
  597. df.dateFormat = @"HH:mm";
  598. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  599. }
  600. #pragma mark - StringUtil
  601. + (NSNumberFormatter *)numberFormatter {
  602. static NSNumberFormatter *__shareNumberFormatter = nil;
  603. static dispatch_once_t onceToken;
  604. dispatch_once(&onceToken, ^{
  605. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  606. NSLocale *locale = [NSLocale currentLocale];
  607. [__shareNumberFormatter setLocale:locale];
  608. });
  609. return __shareNumberFormatter;
  610. }
  611. + (NSString *)numberString:(NSInteger)number {
  612. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  613. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  614. formatter.usesGroupingSeparator = YES;
  615. [formatter setGroupingSeparator:@","];
  616. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  617. return formattedString;
  618. }
  619. + (NSString *)currencyString:(NSInteger)number {
  620. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  621. if (number <= 0) {
  622. return currency;
  623. }
  624. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  625. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  626. formatter.usesGroupingSeparator = YES;
  627. [formatter setGroupingSeparator:@","];
  628. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  629. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  630. return currency;
  631. }
  632. + (NSString *)currencyString2:(NSInteger)number {
  633. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  634. if (number <= 0) {
  635. return currency;
  636. }
  637. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  638. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  639. formatter.usesGroupingSeparator = YES;
  640. [formatter setGroupingSeparator:@","];
  641. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  642. currency = [NSString stringWithFormat:@"%@원", formattedString];
  643. return currency;
  644. }
  645. + (NSString *)svcNoString:(NSString *)svcNo {
  646. //0103333333
  647. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  648. if (svcNo.length == 10) {
  649. [tmpSvcNo insertString:@"-" atIndex:3];
  650. [tmpSvcNo insertString:@"-" atIndex:7];
  651. } else if (svcNo.length == 11) {
  652. [tmpSvcNo insertString:@"-" atIndex:3];
  653. [tmpSvcNo insertString:@"-" atIndex:8];
  654. }
  655. return tmpSvcNo;
  656. }
  657. + (NSString *)cutSaName:(NSString *)saName {
  658. NSRange range = [saName rangeOfString:@"]"];
  659. NSString *rSaName = nil;
  660. if (range.location != NSNotFound) {
  661. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  662. }
  663. return rSaName;
  664. }
  665. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  666. NSInteger rvalue = 0;
  667. NSString *tmp = [NSString stringWithString:currency];
  668. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  669. if (fRange.location == currency.length-1) {
  670. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  671. }
  672. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  673. rvalue = [tmp intValue];
  674. return rvalue;
  675. }
  676. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  677. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  678. return phoneNumber;
  679. }
  680. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  681. NSInteger lastIndex = phoneNumber.length - 3;
  682. [rString insertString:@"-" atIndex:3];
  683. [rString insertString:@"-" atIndex:lastIndex];
  684. return rString;
  685. }
  686. + (NSString *)formattedIAId:(NSString *)iaId {
  687. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  688. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  689. return formatIAId;
  690. }
  691. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  692. NSInteger count = 0, length = [occurString length];
  693. NSRange range = NSMakeRange(0, length);
  694. while(range.location != NSNotFound) {
  695. range = [occurString rangeOfString:occurString options:0 range:range];
  696. if(range.location != NSNotFound) {
  697. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  698. count++;
  699. }
  700. }
  701. return count;
  702. }
  703. +(NSString *)URLEncoding:(NSString *)sender{
  704. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  705. NULL,
  706. (CFStringRef)sender,
  707. NULL,
  708. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  709. kCFStringEncodingUTF8 ));
  710. return encodedString;
  711. }
  712. +(NSString *)URLDecoding:(NSString *)sender {
  713. // Decode a percent escape encoded string.
  714. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  715. (CFStringRef) sender,
  716. CFSTR(""),
  717. kCFStringEncodingUTF8));
  718. return decodeString;
  719. }
  720. #pragma getUrlPostUrl
  721. + (NSString *)switchPostUrl:(NSString *)getUrl{
  722. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  723. NSString *splturl = [urlLst objectAtIndex:1];
  724. return splturl;
  725. }
  726. + (NSString *)getUrl:(NSString *)getUrl{
  727. NSString *url;
  728. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  729. url = [urlLst objectAtIndex:0];
  730. return url;
  731. }
  732. + (BOOL)stringContainsEmoji:(NSString *)string {
  733. __block BOOL returnValue = NO;
  734. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  735. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  736. const unichar hs = [substring characterAtIndex:0];
  737. // surrogate pair
  738. if (0xd800 <= hs && hs <= 0xdbff) {
  739. if (substring.length > 1) {
  740. const unichar ls = [substring characterAtIndex:1];
  741. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  742. if (0x1d000 <= uc && uc <= 0x1f77f) {
  743. returnValue = YES;
  744. }
  745. }
  746. } else if (substring.length > 1) {
  747. const unichar ls = [substring characterAtIndex:1];
  748. if (ls == 0x20e3) {
  749. returnValue = YES;
  750. }
  751. } else {
  752. // non surrogate
  753. if (0x2100 <= hs && hs <= 0x27ff) {
  754. returnValue = YES;
  755. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  756. returnValue = YES;
  757. } else if (0x2934 <= hs && hs <= 0x2935) {
  758. returnValue = YES;
  759. } else if (0x3297 <= hs && hs <= 0x3299) {
  760. returnValue = YES;
  761. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  762. returnValue = YES;
  763. }
  764. }
  765. }];
  766. return returnValue;
  767. }
  768. #pragma mark - TimeZone Dictionary
  769. + (SortDictionary *)timeZoneDict {
  770. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  771. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  772. return [[SortDictionary alloc] initWithDictionary:dic];
  773. }
  774. @end