CommonUtil.m 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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. + (NSCalendar *)calendar2 {
  320. NSCalendar *cal = [NSCalendar currentCalendar];
  321. [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0900"]];
  322. return cal;
  323. }
  324. + (NSDateFormatter *)dateFormatter {
  325. static NSDateFormatter *__shareDateFormatter = nil;
  326. static dispatch_once_t onceToken;
  327. dispatch_once(&onceToken, ^{
  328. __shareDateFormatter = [[NSDateFormatter alloc] init];
  329. NSLocale *locale = [NSLocale currentLocale];
  330. [__shareDateFormatter setLocale:locale];
  331. });
  332. return __shareDateFormatter;
  333. }
  334. + (NSString *)currentDate {
  335. NSDateFormatter *df = [CommonUtil dateFormatter];
  336. df.dateFormat = @"YYYY.MM.dd";
  337. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  338. return title;
  339. }
  340. + (NSString *)currentMonth {
  341. NSDateFormatter *df = [CommonUtil dateFormatter];
  342. df.dateFormat = @"YYYY.MM";
  343. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  344. return title;
  345. }
  346. + (NSDateComponents *)dateComponents:(NSDate *)date {
  347. NSCalendar *calendar = [CommonUtil calendar];
  348. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  349. NSCalendarUnitMonth |
  350. NSCalendarUnitDay |
  351. NSCalendarUnitHour |
  352. NSCalendarUnitMinute|
  353. NSCalendarUnitSecond|
  354. NSCalendarUnitTimeZone) fromDate:date];
  355. return components;
  356. }
  357. + (NSDateComponents *)dateComponents:(NSDate *)date timezone:(NSTimeZone *)timezone {
  358. NSCalendar *calendar = [CommonUtil calendar];
  359. [calendar setTimeZone:timezone];
  360. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  361. NSCalendarUnitMonth |
  362. NSCalendarUnitDay |
  363. NSCalendarUnitHour |
  364. NSCalendarUnitMinute|
  365. NSCalendarUnitSecond|
  366. NSCalendarUnitTimeZone) fromDate:date];
  367. return components;
  368. }
  369. //Date객체를 String객체로 전환
  370. + (NSString *)stringFromDate:(NSDate *)date {
  371. NSDateFormatter *df = [CommonUtil dateFormatter];
  372. df.dateFormat = @"YYYY/MM/dd";
  373. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  374. }
  375. + (NSString *)stringFromDateTime:(NSDate *)date {
  376. NSDateFormatter *df = [CommonUtil dateFormatter];
  377. df.dateFormat = @"yyyyMMddHHmmss";
  378. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  379. }
  380. + (NSString *)birthStringFromDate:(NSDate *)date {
  381. NSDateFormatter *df = [CommonUtil dateFormatter];
  382. df.dateFormat = @"YYYYMMdd";
  383. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  384. }
  385. + (NSString *)stringFromDate2:(NSDate *)date {
  386. NSDateFormatter *df = [CommonUtil dateFormatter];
  387. df.dateFormat = @"YYYY-MM-dd";
  388. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  389. }
  390. + (NSString *)stringFromString:(NSString *)dateString {
  391. NSDateComponents *components = [CommonUtil dateComponentsFromString:dateString];
  392. return [CommonUtil stringFromDateComponents:components];
  393. }
  394. + (NSDateComponents *)dateComponentsFromString:(NSString *)dateString {
  395. NSDateComponents *dateComp = nil;
  396. if (dateString && dateString.length == 6) {//19990101 타입
  397. dateComp = [[NSDateComponents alloc] init];
  398. dateComp.year = [[dateString substringToIndex:4] intValue];
  399. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  400. } else if (dateString && dateString.length == 8) {//19990101 타입
  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. } else if (dateString && dateString.length == 14) {//19990101010101 타입
  406. dateComp = [[NSDateComponents alloc] init];
  407. dateComp.year = [[dateString substringToIndex:4] intValue];
  408. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  409. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  410. dateComp.hour = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
  411. dateComp.minute = [[dateString substringWithRange:NSMakeRange(10, 2)] intValue];
  412. dateComp.second = [[dateString substringWithRange:NSMakeRange(12, 2)] intValue];
  413. } else if ([dateString rangeOfString:@"-"].location != NSNotFound) {
  414. NSArray *dateArray = [dateString componentsSeparatedByString:@"-"];
  415. if (dateArray && dateArray.count > 0) {
  416. dateComp = [[NSDateComponents alloc] init];
  417. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  418. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  419. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  420. }
  421. } else if ([dateString rangeOfString:@"/"].location != NSNotFound) {
  422. NSArray *dateArray = [dateString componentsSeparatedByString:@"/"];
  423. if (dateArray && dateArray.count > 0) {
  424. dateComp = [[NSDateComponents alloc] init];
  425. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  426. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  427. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  428. }
  429. } else if ([dateString rangeOfString:@"."].location != NSNotFound) {
  430. NSArray *dateArray = [dateString componentsSeparatedByString:@"."];
  431. if (dateArray && dateArray.count > 0) {
  432. dateComp = [[NSDateComponents alloc] init];
  433. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  434. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  435. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  436. }
  437. }
  438. return dateComp;
  439. }
  440. + (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
  441. NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
  442. [df_local setTimeZone:[NSTimeZone systemTimeZone]];
  443. [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
  444. NSDate *locTime = [df_local dateFromString:utcString];
  445. return [CommonUtil dateComponents:locTime];
  446. }
  447. + (NSDate *)dateFromDateString:(NSString *)dateString {
  448. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  449. NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
  450. return newDate;
  451. }
  452. + (NSString *)stringFromDateComponents:(NSDateComponents *)components {
  453. NSMutableString *rString = [NSMutableString new];
  454. if (components.year > 0) {
  455. [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
  456. }
  457. if (components.month > 0) {
  458. if (rString.length > 0) {
  459. [rString appendString:@" "];
  460. }
  461. [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
  462. }
  463. if (components.day > 0) {
  464. if (rString.length > 0) {
  465. [rString appendString:@" "];
  466. }
  467. [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
  468. }
  469. return rString;
  470. }
  471. + (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
  472. NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
  473. NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
  474. NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
  475. return rString;
  476. }
  477. + (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
  478. NSMutableString *rString = [NSMutableString new];
  479. if (components.year > 0) {
  480. [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
  481. }
  482. if (components.month > 0) {
  483. if (components.month < 10) {
  484. [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
  485. } else {
  486. [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
  487. }
  488. }
  489. return rString;
  490. }
  491. + (NSString *)paramMonthFromDateString:(NSString *)dateString {
  492. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  493. ds.day = 1;
  494. NSDateFormatter *df = [CommonUtil dateFormatter];
  495. df.dateFormat = @"YYYYMM";
  496. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  497. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  498. }
  499. + (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
  500. NSDateComponents *ds = [CommonUtil dateComponents:date];
  501. ds.day += day;
  502. NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
  503. return adjustDate;
  504. }
  505. //현재 로컬시간을 UTC로 변환합니다.
  506. + (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
  507. NSDateFormatter *df = [CommonUtil dateFormatter];
  508. [df setDateFormat:@"yyyyMMddHHmmss"];
  509. NSDate *locDate = [df dateFromString:locDateString];
  510. NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
  511. dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
  512. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  513. [dfu setTimeZone:utc];
  514. NSString *timeStamp = [dfu stringFromDate:locDate];
  515. timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
  516. return timeStamp;
  517. }
  518. //UTC 시간을 현재 로컬 시간을 변환합니다.
  519. + (NSString *)localDateFromUTC:(NSString *)utcDateString {
  520. NSDateFormatter *df = [CommonUtil dateFormatter];
  521. [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
  522. NSDate *utcDate = [df dateFromString:utcDateString];
  523. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  524. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  525. [dfl setDateFormat:@"yyyyMMddHHmmss"];
  526. NSString* localString = [dfl stringFromDate:utcDate];
  527. return localString;
  528. }
  529. + (NSString *)localDateFromUTC2:(NSString *)utcDateString {
  530. NSDateFormatter *df = [[CommonUtil dateFormatter] copy];
  531. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  532. [df setTimeZone:utc];
  533. [df setDateFormat:@"yyyyMMddHHmmss"];
  534. NSDate *utcDate = [df dateFromString:utcDateString];
  535. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  536. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  537. [dfl setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  538. NSString* localString = [dfl stringFromDate:utcDate];
  539. return localString;
  540. }
  541. + (NSString *)formattedDate:(NSString *)dateString {
  542. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  543. NSDateFormatter *df = [CommonUtil dateFormatter];
  544. df.dateFormat = @"YYYY년 M월 d일";
  545. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  546. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  547. }
  548. + (NSString *)formattedDate2:(NSString *)dateString {
  549. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  550. NSDateFormatter *df = [CommonUtil dateFormatter];
  551. df.dateFormat = @"YYYY.MM.dd";
  552. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  553. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  554. }
  555. //기본 날짜포맷을 반환
  556. + (NSString *)formattedDate3:(NSString *)datetime {
  557. NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
  558. NSDateFormatter *df = [CommonUtil dateFormatter];
  559. df.dateFormat = @"YYYY년 MM월 dd일";
  560. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  561. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  562. }
  563. + (NSString *)formattedDate4:(NSString *)datetime {
  564. NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
  565. NSDateFormatter *df = [CommonUtil dateFormatter];
  566. df.dateFormat = @"YYYY-MM-dd HH:mm";
  567. NSDate *date = [[CommonUtil calendar2] dateFromComponents:ds];
  568. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  569. }
  570. + (NSString *)formattedMonthDate:(NSString *)dateString {
  571. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  572. NSDateFormatter *df = [CommonUtil dateFormatter];
  573. df.dateFormat = @"YYYY.MM";
  574. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  575. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  576. }
  577. #pragma mark - TimeUtil
  578. + (NSString *)formattedTime:(NSString *)timeString {
  579. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  580. NSDateFormatter *df = [CommonUtil dateFormatter];
  581. df.dateFormat = @"HH시 mm분";
  582. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  583. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  584. }
  585. + (NSString *)formattedTime2:(NSString *)timeString {
  586. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  587. NSDateFormatter *df = [CommonUtil dateFormatter];
  588. df.dateFormat = @"HH시 mm분";
  589. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  590. if ([period isEqualToString:@"오후"]) {
  591. ds.hour -= 12;
  592. }
  593. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  594. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  595. }
  596. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  597. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  598. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  599. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  600. NSString *hour = [timeArray firstObject];
  601. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  602. NSString *minute = [timeArray lastObject];
  603. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  604. dateComp.hour = [hour intValue];
  605. dateComp.minute = [minute intValue];
  606. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  607. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  608. if (timeArray && timeArray.count > 0) {
  609. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  610. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  611. }
  612. }
  613. return dateComp;
  614. }
  615. + (NSString *)stringFromTime:(NSDate *)date {
  616. NSDateFormatter *df = [CommonUtil dateFormatter];
  617. df.dateFormat = @"HH:mm";
  618. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  619. }
  620. #pragma mark - StringUtil
  621. + (NSNumberFormatter *)numberFormatter {
  622. static NSNumberFormatter *__shareNumberFormatter = nil;
  623. static dispatch_once_t onceToken;
  624. dispatch_once(&onceToken, ^{
  625. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  626. NSLocale *locale = [NSLocale currentLocale];
  627. [__shareNumberFormatter setLocale:locale];
  628. });
  629. return __shareNumberFormatter;
  630. }
  631. + (NSString *)numberString:(NSInteger)number {
  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. return formattedString;
  638. }
  639. + (NSString *)currencyString:(NSInteger)number {
  640. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  641. if (number <= 0) {
  642. return currency;
  643. }
  644. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  645. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  646. formatter.usesGroupingSeparator = YES;
  647. [formatter setGroupingSeparator:@","];
  648. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  649. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  650. return currency;
  651. }
  652. + (NSString *)currencyString2:(NSInteger)number {
  653. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  654. if (number <= 0) {
  655. return currency;
  656. }
  657. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  658. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  659. formatter.usesGroupingSeparator = YES;
  660. [formatter setGroupingSeparator:@","];
  661. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  662. currency = [NSString stringWithFormat:@"%@원", formattedString];
  663. return currency;
  664. }
  665. + (NSString *)svcNoString:(NSString *)svcNo {
  666. //0103333333
  667. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  668. if (svcNo.length == 10) {
  669. [tmpSvcNo insertString:@"-" atIndex:3];
  670. [tmpSvcNo insertString:@"-" atIndex:7];
  671. } else if (svcNo.length == 11) {
  672. [tmpSvcNo insertString:@"-" atIndex:3];
  673. [tmpSvcNo insertString:@"-" atIndex:8];
  674. }
  675. return tmpSvcNo;
  676. }
  677. + (NSString *)cutSaName:(NSString *)saName {
  678. NSRange range = [saName rangeOfString:@"]"];
  679. NSString *rSaName = nil;
  680. if (range.location != NSNotFound) {
  681. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  682. }
  683. return rSaName;
  684. }
  685. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  686. NSInteger rvalue = 0;
  687. NSString *tmp = [NSString stringWithString:currency];
  688. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  689. if (fRange.location == currency.length-1) {
  690. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  691. }
  692. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  693. rvalue = [tmp intValue];
  694. return rvalue;
  695. }
  696. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  697. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  698. return phoneNumber;
  699. }
  700. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  701. NSInteger lastIndex = phoneNumber.length - 3;
  702. [rString insertString:@"-" atIndex:3];
  703. [rString insertString:@"-" atIndex:lastIndex];
  704. return rString;
  705. }
  706. + (NSString *)formattedIAId:(NSString *)iaId {
  707. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  708. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  709. return formatIAId;
  710. }
  711. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  712. NSInteger count = 0, length = [occurString length];
  713. NSRange range = NSMakeRange(0, length);
  714. while(range.location != NSNotFound) {
  715. range = [occurString rangeOfString:occurString options:0 range:range];
  716. if(range.location != NSNotFound) {
  717. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  718. count++;
  719. }
  720. }
  721. return count;
  722. }
  723. +(NSString *)URLEncoding:(NSString *)sender{
  724. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  725. NULL,
  726. (CFStringRef)sender,
  727. NULL,
  728. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  729. kCFStringEncodingUTF8 ));
  730. return encodedString;
  731. }
  732. +(NSString *)URLDecoding:(NSString *)sender {
  733. // Decode a percent escape encoded string.
  734. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  735. (CFStringRef) sender,
  736. CFSTR(""),
  737. kCFStringEncodingUTF8));
  738. return decodeString;
  739. }
  740. #pragma getUrlPostUrl
  741. + (NSString *)switchPostUrl:(NSString *)getUrl{
  742. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  743. NSString *splturl = [urlLst objectAtIndex:1];
  744. return splturl;
  745. }
  746. + (NSString *)getUrl:(NSString *)getUrl{
  747. NSString *url;
  748. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  749. url = [urlLst objectAtIndex:0];
  750. return url;
  751. }
  752. + (BOOL)stringContainsEmoji:(NSString *)string {
  753. __block BOOL returnValue = NO;
  754. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  755. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  756. const unichar hs = [substring characterAtIndex:0];
  757. // surrogate pair
  758. if (0xd800 <= hs && hs <= 0xdbff) {
  759. if (substring.length > 1) {
  760. const unichar ls = [substring characterAtIndex:1];
  761. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  762. if (0x1d000 <= uc && uc <= 0x1f77f) {
  763. returnValue = YES;
  764. }
  765. }
  766. } else if (substring.length > 1) {
  767. const unichar ls = [substring characterAtIndex:1];
  768. if (ls == 0x20e3) {
  769. returnValue = YES;
  770. }
  771. } else {
  772. // non surrogate
  773. if (0x2100 <= hs && hs <= 0x27ff) {
  774. returnValue = YES;
  775. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  776. returnValue = YES;
  777. } else if (0x2934 <= hs && hs <= 0x2935) {
  778. returnValue = YES;
  779. } else if (0x3297 <= hs && hs <= 0x3299) {
  780. returnValue = YES;
  781. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  782. returnValue = YES;
  783. }
  784. }
  785. }];
  786. return returnValue;
  787. }
  788. #pragma mark - TimeZone Dictionary
  789. + (SortDictionary *)timeZoneDict {
  790. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  791. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  792. return [[SortDictionary alloc] initWithDictionary:dic];
  793. }
  794. #pragma mark - Color
  795. +(UIColor *)convertFromRGBToUIColor:(NSString *)hexRGB {
  796. NSString *cleanString = [hexRGB stringByReplacingOccurrencesOfString:@"#" withString:@""];
  797. if ([cleanString length] == 3) {
  798. cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", [cleanString substringWithRange:NSMakeRange(0, 1)], [cleanString substringWithRange:NSMakeRange(0, 1)],
  799. [cleanString substringWithRange:NSMakeRange(1, 1)], [cleanString substringWithRange:NSMakeRange(1, 1)],
  800. [cleanString substringWithRange:NSMakeRange(2, 1)], [cleanString substringWithRange:NSMakeRange(2, 1)]];
  801. }
  802. if ([cleanString length] == 6) {
  803. cleanString = [cleanString stringByAppendingString:@"ff"];
  804. }
  805. unsigned int baseValue;
  806. [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
  807. float red = ((baseValue >> 24) & 0xFF) / 255.0f;
  808. float green = ((baseValue >> 16) & 0xFF) / 255.0f;
  809. float blue = ((baseValue >> 8) & 0xFF) / 255.0f;
  810. float alpha = ((baseValue >> 0) & 0xFF) / 255.0f;
  811. return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
  812. }
  813. @end