CommonUtil.m 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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 *)formattedDate:(NSString *)dateString {
  517. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  518. NSDateFormatter *df = [CommonUtil dateFormatter];
  519. df.dateFormat = @"YYYY/MM/dd";
  520. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  521. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  522. }
  523. + (NSString *)formattedDate2:(NSString *)dateString {
  524. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  525. NSDateFormatter *df = [CommonUtil dateFormatter];
  526. df.dateFormat = @"YYYY.MM.dd";
  527. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  528. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  529. }
  530. //기본 날짜포맷을 반환
  531. + (NSString *)formattedDate3:(NSString *)datetime {
  532. NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
  533. NSDateFormatter *df = [CommonUtil dateFormatter];
  534. df.dateFormat = @"YYYY년 MM월 dd일";
  535. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  536. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  537. }
  538. + (NSString *)formattedMonthDate:(NSString *)dateString {
  539. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  540. NSDateFormatter *df = [CommonUtil dateFormatter];
  541. df.dateFormat = @"YYYY.MM";
  542. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  543. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  544. }
  545. #pragma mark - TimeUtil
  546. + (NSString *)formattedTime:(NSString *)timeString {
  547. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  548. NSDateFormatter *df = [CommonUtil dateFormatter];
  549. df.dateFormat = @"HH시 mm분";
  550. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  551. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  552. }
  553. + (NSString *)formattedTime2:(NSString *)timeString {
  554. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  555. NSDateFormatter *df = [CommonUtil dateFormatter];
  556. df.dateFormat = @"HH시 mm분";
  557. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  558. if ([period isEqualToString:@"오후"]) {
  559. ds.hour -= 12;
  560. }
  561. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  562. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  563. }
  564. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  565. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  566. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  567. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  568. NSString *hour = [timeArray firstObject];
  569. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  570. NSString *minute = [timeArray lastObject];
  571. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  572. dateComp.hour = [hour intValue];
  573. dateComp.minute = [minute intValue];
  574. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  575. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  576. if (timeArray && timeArray.count > 0) {
  577. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  578. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  579. }
  580. }
  581. return dateComp;
  582. }
  583. + (NSString *)stringFromTime:(NSDate *)date {
  584. NSDateFormatter *df = [CommonUtil dateFormatter];
  585. df.dateFormat = @"HH:mm";
  586. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  587. }
  588. #pragma mark - StringUtil
  589. + (NSNumberFormatter *)numberFormatter {
  590. static NSNumberFormatter *__shareNumberFormatter = nil;
  591. static dispatch_once_t onceToken;
  592. dispatch_once(&onceToken, ^{
  593. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  594. NSLocale *locale = [NSLocale currentLocale];
  595. [__shareNumberFormatter setLocale:locale];
  596. });
  597. return __shareNumberFormatter;
  598. }
  599. + (NSString *)numberString:(NSInteger)number {
  600. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  601. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  602. formatter.usesGroupingSeparator = YES;
  603. [formatter setGroupingSeparator:@","];
  604. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  605. return formattedString;
  606. }
  607. + (NSString *)currencyString:(NSInteger)number {
  608. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  609. if (number <= 0) {
  610. return currency;
  611. }
  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. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  618. return currency;
  619. }
  620. + (NSString *)currencyString2:(NSInteger)number {
  621. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  622. if (number <= 0) {
  623. return currency;
  624. }
  625. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  626. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  627. formatter.usesGroupingSeparator = YES;
  628. [formatter setGroupingSeparator:@","];
  629. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  630. currency = [NSString stringWithFormat:@"%@원", formattedString];
  631. return currency;
  632. }
  633. + (NSString *)svcNoString:(NSString *)svcNo {
  634. //0103333333
  635. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  636. if (svcNo.length == 10) {
  637. [tmpSvcNo insertString:@"-" atIndex:3];
  638. [tmpSvcNo insertString:@"-" atIndex:7];
  639. } else if (svcNo.length == 11) {
  640. [tmpSvcNo insertString:@"-" atIndex:3];
  641. [tmpSvcNo insertString:@"-" atIndex:8];
  642. }
  643. return tmpSvcNo;
  644. }
  645. + (NSString *)cutSaName:(NSString *)saName {
  646. NSRange range = [saName rangeOfString:@"]"];
  647. NSString *rSaName = nil;
  648. if (range.location != NSNotFound) {
  649. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  650. }
  651. return rSaName;
  652. }
  653. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  654. NSInteger rvalue = 0;
  655. NSString *tmp = [NSString stringWithString:currency];
  656. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  657. if (fRange.location == currency.length-1) {
  658. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  659. }
  660. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  661. rvalue = [tmp intValue];
  662. return rvalue;
  663. }
  664. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  665. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  666. return phoneNumber;
  667. }
  668. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  669. NSInteger lastIndex = phoneNumber.length - 3;
  670. [rString insertString:@"-" atIndex:3];
  671. [rString insertString:@"-" atIndex:lastIndex];
  672. return rString;
  673. }
  674. + (NSString *)formattedIAId:(NSString *)iaId {
  675. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  676. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  677. return formatIAId;
  678. }
  679. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  680. NSInteger count = 0, length = [occurString length];
  681. NSRange range = NSMakeRange(0, length);
  682. while(range.location != NSNotFound) {
  683. range = [occurString rangeOfString:occurString options:0 range:range];
  684. if(range.location != NSNotFound) {
  685. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  686. count++;
  687. }
  688. }
  689. return count;
  690. }
  691. +(NSString *)URLEncoding:(NSString *)sender{
  692. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  693. NULL,
  694. (CFStringRef)sender,
  695. NULL,
  696. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  697. kCFStringEncodingUTF8 ));
  698. return encodedString;
  699. }
  700. +(NSString *)URLDecoding:(NSString *)sender {
  701. // Decode a percent escape encoded string.
  702. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  703. (CFStringRef) sender,
  704. CFSTR(""),
  705. kCFStringEncodingUTF8));
  706. return decodeString;
  707. }
  708. #pragma getUrlPostUrl
  709. + (NSString *)switchPostUrl:(NSString *)getUrl{
  710. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  711. NSString *splturl = [urlLst objectAtIndex:1];
  712. return splturl;
  713. }
  714. + (NSString *)getUrl:(NSString *)getUrl{
  715. NSString *url;
  716. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  717. url = [urlLst objectAtIndex:0];
  718. return url;
  719. }
  720. + (BOOL)stringContainsEmoji:(NSString *)string {
  721. __block BOOL returnValue = NO;
  722. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  723. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  724. const unichar hs = [substring characterAtIndex:0];
  725. // surrogate pair
  726. if (0xd800 <= hs && hs <= 0xdbff) {
  727. if (substring.length > 1) {
  728. const unichar ls = [substring characterAtIndex:1];
  729. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  730. if (0x1d000 <= uc && uc <= 0x1f77f) {
  731. returnValue = YES;
  732. }
  733. }
  734. } else if (substring.length > 1) {
  735. const unichar ls = [substring characterAtIndex:1];
  736. if (ls == 0x20e3) {
  737. returnValue = YES;
  738. }
  739. } else {
  740. // non surrogate
  741. if (0x2100 <= hs && hs <= 0x27ff) {
  742. returnValue = YES;
  743. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  744. returnValue = YES;
  745. } else if (0x2934 <= hs && hs <= 0x2935) {
  746. returnValue = YES;
  747. } else if (0x3297 <= hs && hs <= 0x3299) {
  748. returnValue = YES;
  749. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  750. returnValue = YES;
  751. }
  752. }
  753. }];
  754. return returnValue;
  755. }
  756. #pragma mark - TimeZone Dictionary
  757. + (SortDictionary *)timeZoneDict {
  758. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  759. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  760. return [[SortDictionary alloc] initWithDictionary:dic];
  761. }
  762. @end