CommonUtil.m 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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 "UIDeviceUtil.h"
  13. #import "Common.h"
  14. #import "Definitions.h"
  15. #import "CommonUtil.h"
  16. #import "SortDictionary.h"
  17. #import "AppDelegate.h"
  18. #define ksEmptyString @""
  19. @implementation CommonUtil
  20. #pragma mark - System Util
  21. + (NSString *)applicationVersion {
  22. NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
  23. // CGFloat version = [[[UIDevice currentDevice] ] floatValue];
  24. // CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
  25. return strVersion;
  26. }
  27. + (NSString *)applicationShortVersion {
  28. NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  29. // CGFloat version = [[[UIDevice currentDevice] ] floatValue];
  30. // CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
  31. return strVersion;
  32. }
  33. + (NSString *)bundleIdentifier {
  34. return [[NSBundle mainBundle] bundleIdentifier];
  35. }
  36. + (CGFloat)deviceSystemVersion {
  37. static NSUInteger _deviceSystemVersion = -1.0f;
  38. static dispatch_once_t onceToken;
  39. dispatch_once(&onceToken, ^{
  40. _deviceSystemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
  41. });
  42. return _deviceSystemVersion;
  43. }
  44. + (NSString *)uniqueIdentifier {
  45. //uuid 로 변경
  46. NSString *identifier = ksEmptyString;
  47. // NSString *identifier = [[OSUserDefaults defaults] objectForKey:@"MAC_ADD"];
  48. //
  49. // if ([identifier length] == 0 || [identifier isEqual:ksEmptyString]) {
  50. // CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  51. // NSString *string = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
  52. //
  53. // [[OSUserDefaults defaults] setObject:string forKey:@"MAC_ADD"];
  54. // [[OSUserDefaults defaults] synchronize];
  55. // identifier = string;
  56. // }
  57. NSLog(@"===identifier===%@", identifier);
  58. return identifier;
  59. }
  60. + (NSString *)deviceName {//////////////////
  61. return [UIDevice currentDevice].name;
  62. }
  63. + (CGFloat)hardwareVersion {
  64. return [UIDeviceUtil hardwareNumber:[UIDeviceUtil hardware]];
  65. }
  66. + (NSUInteger)hardware {
  67. return [UIDeviceUtil hardware];
  68. }
  69. + (void)showCurrentDevice {
  70. UIDevice *device = [UIDevice currentDevice];
  71. NSMutableString *print = [NSMutableString new];
  72. [print appendFormat:@"\n%@\n", device.name];
  73. [print appendFormat:@"%@\n", device.systemName];
  74. [print appendFormat:@"%@\n", device.model];
  75. [print appendFormat:@"%@\n", device.localizedModel];
  76. [print appendFormat:@"%zd\n", device.userInterfaceIdiom];
  77. [print appendFormat:@"%@\n", [UIDeviceUtil hardwareSimpleDescription]];
  78. }
  79. #pragma makr - Locale
  80. + (NSString *)countryCode {
  81. return [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
  82. }
  83. #pragma mark - Network Util
  84. + (BOOL)roamingCheck {
  85. CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
  86. CTCarrier *carrier = [networkInfo subscriberCellularProvider];
  87. NSString *carrierName = [carrier carrierName]; //통신사를 받아올 수 있다.
  88. NSLog(@"Carrier: %@", carrierName);
  89. NSString *mnc = [carrier mobileNetworkCode]; //통신사를 받아올 수 있다.
  90. NSLog(@"mnc: %@", mnc);
  91. NSString *mcc = [carrier mobileCountryCode]; // 국가코드를 받아올 수 있다.
  92. NSLog(@"Mobile Country Code (MCC): %@", mcc);
  93. BOOL network = NO;
  94. if ([mnc isEqualToString:@"05"] || [mnc isEqualToString:@"06"] || [mnc isEqualToString:@"08"] ) { //mnc code
  95. if ([mcc isEqualToString:@"450"]) { //국가 코드
  96. network = YES;
  97. }
  98. }
  99. return network;
  100. }
  101. + (BOOL)isOnPhoneCall {
  102. CTCallCenter *callCenter = [[CTCallCenter alloc] init];
  103. for (CTCall *call in callCenter.currentCalls) {
  104. if (call.callState == CTCallStateConnected) {
  105. return YES;
  106. }
  107. }
  108. return NO;
  109. }
  110. #pragma mark - File Util
  111. +(NSString*)getPath:(NSString *)lastPath {
  112. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  113. NSString *documentsDirectory= [paths objectAtIndex:0];
  114. return [documentsDirectory stringByAppendingPathComponent:lastPath];
  115. }
  116. +(BOOL)isExistFile:(NSString*)filePath {
  117. BOOL isExist = NO;
  118. NSFileManager *fileManager = [NSFileManager defaultManager];
  119. if ([fileManager fileExistsAtPath:filePath])
  120. isExist = YES;
  121. else
  122. isExist = NO;
  123. return isExist;
  124. }
  125. + (BOOL)createFile:(NSString*)filePath {
  126. BOOL bCreate = NO;
  127. NSLog(@"document file path : %@", filePath);
  128. //파일의 존재 유무 검사 및 없으면 생성
  129. NSFileManager *fileManager = [NSFileManager defaultManager];
  130. BOOL isFile = [fileManager fileExistsAtPath:filePath];
  131. if (isFile | [fileManager createFileAtPath:filePath contents:nil attributes:nil]){
  132. bCreate = YES;
  133. }else{
  134. bCreate = NO;
  135. }
  136. return bCreate;
  137. }
  138. + (BOOL)deleteFile:(NSString *)fileName {
  139. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  140. NSString *filepath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], fileName];
  141. NSFileManager *fileManager = [NSFileManager defaultManager];
  142. [fileManager removeItemAtPath:filepath error:nil];
  143. return YES;
  144. }
  145. #pragma mark - UI Util
  146. + (id)instantiateViewControllerWithIdentifier:(NSString *)identifier storyboardName:(NSString *)storyboardName
  147. {
  148. UIStoryboard *sb = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
  149. return [sb instantiateViewControllerWithIdentifier:identifier];
  150. }
  151. + (UIViewController *)currentViewController {
  152. id appDelegate = [UIApplication sharedApplication].delegate;
  153. UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
  154. if (vc.presentedViewController) {
  155. vc = vc.presentedViewController;
  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. if ([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. //이미지사이즈를 늘림 - 나인패치
  240. + (UIImage *)stretchedImage:(UIImage *)srcImage expectSize:(CGSize)size {
  241. int st_width = size.width > srcImage.size.width ? (size.width - srcImage.size.width) / 2 : 0;
  242. int st_height = size.height > srcImage.size.height ? (size.height - srcImage.size.height) / 2 : 0;
  243. CGFloat capWidth = (st_width / 2);
  244. CGFloat capHeight = (st_height / 2);
  245. if (capWidth > 0) {
  246. capWidth = capWidth >= srcImage.size.width ? srcImage.size.width / 2 : capWidth;
  247. }
  248. if (capHeight > 0) {
  249. capHeight = capHeight >= srcImage.size.width ? srcImage.size.width / 2 : capHeight;
  250. }
  251. return [CommonUtil resizableImageWithCapInsets:UIEdgeInsetsMake(capHeight, capWidth, capHeight, capWidth) resizingMode:UIImageResizingModeStretch img:srcImage];
  252. }
  253. + (CGSize)sizeWithString:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)constrainedToSize lineBreakMode:(NSLineBreakMode)lineBreakMode {
  254. CGSize size = CGSizeZero;
  255. if (IOS_VERSION >= 7.0f) {
  256. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  257. CGRect rect = [attributedText boundingRectWithSize:(CGSize){constrainedToSize.width, CGFLOAT_MAX}
  258. options:NSStringDrawingUsesLineFragmentOrigin
  259. context:nil];
  260. size = rect.size;
  261. }
  262. return size;
  263. }
  264. + (float)sizeWithStringHeight:(NSString *)text font:(UIFont *)font constrainedToSize:(float)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
  265. float size = 0;
  266. if (IOS_VERSION >= 7.0f) {
  267. NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
  268. CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
  269. options:NSStringDrawingUsesLineFragmentOrigin
  270. context:nil];
  271. size = rect.size.height;
  272. }
  273. return size;
  274. }
  275. + (CGFloat)getLabelRealWidth:(UILabel *)label fixedWidth:(CGFloat)fixedWidth {
  276. CGFloat width = 0.0f;
  277. CGRect oriRect = label.frame;
  278. CGRect chRect = label.frame;
  279. chRect.size.width = fixedWidth;
  280. label.frame = chRect;
  281. [label sizeToFit];
  282. width = label.frame.size.width;
  283. label.frame = oriRect;
  284. return width;
  285. }
  286. + (CGFloat)getLabelRealHeight:(UILabel *)label {
  287. CGFloat height = 0.0f;
  288. CGRect oriRect = label.frame;
  289. [label sizeToFit];
  290. height = label.frame.size.height;
  291. label.frame = oriRect;
  292. return height;
  293. }
  294. + (CGSize)getLabelRealSize:(UILabel *)label fixedWdith:(CGFloat)fixedWidth {
  295. CGFloat width = [CommonUtil getLabelRealWidth:label fixedWidth:fixedWidth];
  296. CGFloat height = [CommonUtil getLabelRealHeight:label];
  297. return CGSizeMake(width, height);
  298. }
  299. + (CGSize)getSizeFromString:(NSString *)string font:(UIFont *)font width:(CGFloat)fixedWidth {
  300. if ([string isEqualToString:ksEmptyString]) {
  301. return CGSizeZero;
  302. }
  303. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  304. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  305. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:context];
  306. r = CGRectIntegral(r);
  307. return r.size;
  308. }
  309. + (CGSize)getSizeFromAttributeString:(NSAttributedString *)string width:(CGFloat)fixedWidth {
  310. if ([string.string isEqualToString:ksEmptyString]) {
  311. return CGSizeZero;
  312. }
  313. NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
  314. CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
  315. CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin context:context];
  316. r = CGRectIntegral(r);
  317. return r.size;
  318. }
  319. /**
  320. NIB에서 해당 뷰를 로드함.
  321. @return NSArray * 뷰어레이
  322. */
  323. + (NSArray *)nibViews:(NSString *)nibName {
  324. UINib *nib = [UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]];
  325. return [nib instantiateWithOwner:nil options:nil];
  326. }
  327. #pragma mark - Graphic Util
  328. + (UIImage *)imageWithColor:(UIColor *)color height:(CGFloat)height {
  329. // CGRect appFrame = [UIScreen mainScreen].applicationFrame;
  330. CGFloat y = 0;// appFrame.origin.y > 20 ? 20 : 0;
  331. CGRect rect = CGRectMake(0.0f, y, 1.0f, height);
  332. UIGraphicsBeginImageContext(rect.size);
  333. CGContextRef context = UIGraphicsGetCurrentContext();
  334. CGContextSetFillColorWithColor(context, [color CGColor]);
  335. CGContextFillRect(context, rect);
  336. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  337. UIGraphicsEndImageContext();
  338. return image;
  339. }
  340. + (CGFloat)getImageAspectRatio:(UIImage *)image {
  341. return image.size.width / image.size.height;
  342. }
  343. //해당 이미지를 주어진 크키에 맞추어 리사이즈하여 반환함.
  344. //resize image
  345. + (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth height:(float)resizeHeight {
  346. UIGraphicsBeginImageContext(CGSizeMake(resizeWidth, resizeHeight));
  347. CGContextRef context = UIGraphicsGetCurrentContext();
  348. CGContextTranslateCTM(context, 0.0, resizeHeight);
  349. CGContextScaleCTM(context, 1.0, -1.0);
  350. CGContextDrawImage(context, CGRectMake(0.0, 0.0, resizeWidth, resizeHeight), [image CGImage]);
  351. UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  352. UIGraphicsEndImageContext();
  353. return scaledImage;
  354. }
  355. + (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth {
  356. float ratio = [CommonUtil getImageAspectRatio:image];
  357. float resizeHeight = resizeWidth / ratio;
  358. return [CommonUtil resizeImage:image width:resizeWidth height:resizeHeight];
  359. }
  360. + (UIImage *)resizeImage:(UIImage *)image height:(float)resizeHeight {
  361. float ratio = [CommonUtil getImageAspectRatio:image];
  362. float resizeWidth = resizeHeight * ratio;
  363. return [CommonUtil resizeImage:image width:resizeWidth height:resizeHeight];
  364. }
  365. + (CGRect)convertCropRect:(CGRect)cropRect image:(UIImage *)image {
  366. UIImage *originalImage = image;
  367. CGSize size = originalImage.size;
  368. CGFloat x = cropRect.origin.x;
  369. CGFloat y = cropRect.origin.y;
  370. CGFloat width = cropRect.size.width;
  371. CGFloat height = cropRect.size.height;
  372. UIImageOrientation imageOrientation = originalImage.imageOrientation;
  373. if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
  374. cropRect.origin.x = y;
  375. cropRect.origin.y = size.width - cropRect.size.width - x;
  376. cropRect.size.width = height;
  377. cropRect.size.height = width;
  378. } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
  379. cropRect.origin.x = size.height - cropRect.size.height - y;
  380. cropRect.origin.y = x;
  381. cropRect.size.width = height;
  382. cropRect.size.height = width;
  383. } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
  384. cropRect.origin.x = size.width - cropRect.size.width - x;
  385. cropRect.origin.y = size.height - cropRect.size.height - y;
  386. }
  387. return cropRect;
  388. }
  389. + (UIImage *)croppedImage:(CGRect)cropRect image:(UIImage *)image {
  390. CGImageRef croppedCGImage = CGImageCreateWithImageInRect(image.CGImage ,cropRect);
  391. UIImage *croppedImage = [UIImage imageWithCGImage:croppedCGImage scale:1.0f orientation:image.imageOrientation];
  392. CGImageRelease(croppedCGImage);
  393. return croppedImage;
  394. }
  395. + (UIImage *)resizeImage:(UIImage *)image size:(CGSize)size imageOrientation:(UIImageOrientation)imageOrientation {
  396. if (size.width > image.size.width) {
  397. size.width = image.size.width;
  398. }
  399. if (size.height > image.size.height) {
  400. size.height = image.size.height;
  401. }
  402. CGSize imageSize = image.size;
  403. CGFloat horizontalRatio = size.width / imageSize.width;
  404. CGFloat verticalRatio = size.height / imageSize.height;
  405. CGFloat ratio = MIN(horizontalRatio, verticalRatio);
  406. CGSize targetSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);
  407. UIGraphicsBeginImageContextWithOptions(size, YES, 1.0f);
  408. CGContextRef context = UIGraphicsGetCurrentContext();
  409. CGContextScaleCTM(context, 1.0f, -1.0f);
  410. CGContextTranslateCTM(context, 0.0f, -size.height);
  411. CGAffineTransform transform = CGAffineTransformIdentity;
  412. if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
  413. transform = CGAffineTransformTranslate(transform, 0.0f, size.height);
  414. transform = CGAffineTransformRotate(transform, -M_PI_2);
  415. } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
  416. transform = CGAffineTransformTranslate(transform, size.width, 0.0f);
  417. transform = CGAffineTransformRotate(transform, M_PI_2);
  418. } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
  419. transform = CGAffineTransformTranslate(transform, size.width, size.height);
  420. transform = CGAffineTransformRotate(transform, M_PI);
  421. }
  422. CGContextConcatCTM(context, transform);
  423. CGContextDrawImage(context, CGRectMake((size.width - targetSize.width) / 2, (size.height - targetSize.height) / 2, targetSize.width, targetSize.height), image.CGImage);
  424. UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
  425. UIGraphicsEndImageContext();
  426. return resizedImage;
  427. }
  428. + (UIImage*)getMaskedImageWithSourchImage:(UIImage *)srcImage andMaskImage:(UIImage *)maskImage {
  429. CGImageRef maskRef = maskImage.CGImage;
  430. CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
  431. CGImageGetHeight(maskRef),
  432. CGImageGetBitsPerComponent(maskRef),
  433. CGImageGetBitsPerPixel(maskRef),
  434. CGImageGetBytesPerRow(maskRef),
  435. CGImageGetDataProvider(maskRef), NULL, false);
  436. CGImageRef masked = CGImageCreateWithMask([srcImage CGImage], mask);
  437. CGImageRelease(mask);
  438. UIImage *imageMask = [UIImage imageWithCGImage:masked];
  439. CGImageRelease(masked);
  440. return imageMask;
  441. }
  442. + (UIImage *)imageToGrayScale:(UIImage *)image {
  443. if (!image)
  444. return nil;
  445. int kRed = 1;
  446. int kGreen = 2;
  447. int kBlue = 4;
  448. int colors = kGreen | kBlue | kRed;
  449. int m_width = image.size.width;
  450. int m_height = image.size.height;
  451. uint32_t *rgbImage = (uint32_t *) malloc(m_width * m_height * sizeof(uint32_t));
  452. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  453. CGContextRef context = CGBitmapContextCreate(rgbImage, m_width, m_height, 8, m_width * 4, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  454. CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
  455. CGContextSetShouldAntialias(context, NO);
  456. CGContextDrawImage(context, CGRectMake(0, 0, m_width, m_height), [image CGImage]);
  457. CGContextRelease(context);
  458. CGColorSpaceRelease(colorSpace);
  459. // now convert to grayscale
  460. uint8_t *m_imageData = (uint8_t *) malloc(m_width * m_height);
  461. for(int y = 0; y < m_height; y++) {
  462. for(int x = 0; x < m_width; x++) {
  463. uint32_t rgbPixel=rgbImage[y*m_width+x];
  464. uint32_t sum=0,count=0;
  465. if (colors & kRed) {sum += (rgbPixel>>24)&255; count++;}
  466. if (colors & kGreen) {sum += (rgbPixel>>16)&255; count++;}
  467. if (colors & kBlue) {sum += (rgbPixel>>8)&255; count++;}
  468. m_imageData[y*m_width+x]=sum/count;
  469. }
  470. }
  471. free(rgbImage);
  472. // convert from a gray scale image back into a UIImage
  473. uint8_t *result = (uint8_t *) calloc(m_width * m_height *sizeof(uint32_t), 1);
  474. // process the image back to rgb
  475. for(int i = 0; i < m_height * m_width; i++) {
  476. result[i*4]=0;
  477. int val=m_imageData[i];
  478. result[i*4+1]=val;
  479. result[i*4+2]=val;
  480. result[i*4+3]=val;
  481. }
  482. // create a UIImage
  483. colorSpace = CGColorSpaceCreateDeviceRGB();
  484. context = CGBitmapContextCreate(result, m_width, m_height, 8, m_width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  485. CGImageRef destImage = CGBitmapContextCreateImage(context);
  486. CGContextRelease(context);
  487. CGColorSpaceRelease(colorSpace);
  488. UIImage *resultUIImage = [UIImage imageWithCGImage:destImage];
  489. CGImageRelease(destImage);
  490. free(m_imageData);
  491. // make sure the data will be released by giving it to an autoreleased NSData
  492. [NSData dataWithBytesNoCopy:result length:m_width * m_height];
  493. return resultUIImage;
  494. }
  495. #pragma mark - Date Util
  496. + (NSCalendar *)calendar {
  497. NSCalendar *cal = [NSCalendar currentCalendar];
  498. [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
  499. return cal;
  500. }
  501. + (NSDateFormatter *)dateFormatter {
  502. static NSDateFormatter *__shareDateFormatter = nil;
  503. static dispatch_once_t onceToken;
  504. dispatch_once(&onceToken, ^{
  505. __shareDateFormatter = [[NSDateFormatter alloc] init];
  506. NSLocale *locale = [NSLocale currentLocale];
  507. [__shareDateFormatter setLocale:locale];
  508. });
  509. return __shareDateFormatter;
  510. }
  511. + (NSString *)currentMonth {
  512. NSDateFormatter *df = [CommonUtil dateFormatter];
  513. df.dateFormat = @"YYYY.MM";
  514. NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
  515. return title;
  516. }
  517. + (NSDateComponents *)dateComponents:(NSDate *)date {
  518. NSCalendar *calendar = [CommonUtil calendar];
  519. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  520. NSCalendarUnitMonth |
  521. NSCalendarUnitDay |
  522. NSCalendarUnitHour |
  523. NSCalendarUnitMinute|
  524. NSCalendarUnitSecond|
  525. NSCalendarUnitTimeZone) fromDate:date];
  526. return components;
  527. }
  528. + (NSDateComponents *)dateComponents:(NSDate *)date timezone:(NSTimeZone *)timezone {
  529. NSCalendar *calendar = [CommonUtil calendar];
  530. [calendar setTimeZone:timezone];
  531. NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
  532. NSCalendarUnitMonth |
  533. NSCalendarUnitDay |
  534. NSCalendarUnitHour |
  535. NSCalendarUnitMinute|
  536. NSCalendarUnitSecond|
  537. NSCalendarUnitTimeZone) fromDate:date];
  538. return components;
  539. }
  540. //Date객체를 String객체로 전환
  541. + (NSString *)stringFromDate:(NSDate *)date {
  542. NSDateFormatter *df = [CommonUtil dateFormatter];
  543. df.dateFormat = @"YYYY/MM/dd";
  544. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  545. }
  546. + (NSString *)stringFromDateTime:(NSDate *)date {
  547. NSDateFormatter *df = [CommonUtil dateFormatter];
  548. df.dateFormat = @"yyyyMMddHHmmss";
  549. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  550. }
  551. + (NSString *)birthStringFromDate:(NSDate *)date {
  552. NSDateFormatter *df = [CommonUtil dateFormatter];
  553. df.dateFormat = @"YYYYMMdd";
  554. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  555. }
  556. + (NSString *)stringFromDate2:(NSDate *)date {
  557. NSDateFormatter *df = [CommonUtil dateFormatter];
  558. df.dateFormat = @"YYYY-MM-dd";
  559. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  560. }
  561. + (NSString *)stringFromString:(NSString *)dateString {
  562. NSDateComponents *components = [CommonUtil dateComponentsFromString:dateString];
  563. return [CommonUtil stringFromDateComponents:components];
  564. }
  565. + (NSDateComponents *)dateComponentsFromString:(NSString *)dateString {
  566. NSDateComponents *dateComp = nil;
  567. if (dateString && dateString.length == 6) {//19990101 타입
  568. dateComp = [[NSDateComponents alloc] init];
  569. dateComp.year = [[dateString substringToIndex:4] intValue];
  570. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  571. } else if (dateString && dateString.length == 8) {//19990101 타입
  572. dateComp = [[NSDateComponents alloc] init];
  573. dateComp.year = [[dateString substringToIndex:4] intValue];
  574. dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
  575. dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
  576. } else if ([dateString rangeOfString:@"-"].location != NSNotFound) {
  577. NSArray *dateArray = [dateString componentsSeparatedByString:@"-"];
  578. if (dateArray && dateArray.count > 0) {
  579. dateComp = [[NSDateComponents alloc] init];
  580. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  581. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  582. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  583. }
  584. } else if ([dateString rangeOfString:@"/"].location != NSNotFound) {
  585. NSArray *dateArray = [dateString componentsSeparatedByString:@"/"];
  586. if (dateArray && dateArray.count > 0) {
  587. dateComp = [[NSDateComponents alloc] init];
  588. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  589. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  590. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  591. }
  592. } else if ([dateString rangeOfString:@"."].location != NSNotFound) {
  593. NSArray *dateArray = [dateString componentsSeparatedByString:@"."];
  594. if (dateArray && dateArray.count > 0) {
  595. dateComp = [[NSDateComponents alloc] init];
  596. dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
  597. dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
  598. dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
  599. }
  600. }
  601. return dateComp;
  602. }
  603. + (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
  604. NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
  605. [df_local setTimeZone:[NSTimeZone systemTimeZone]];
  606. [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
  607. NSDate *locTime = [df_local dateFromString:utcString];
  608. return [CommonUtil dateComponents:locTime];
  609. }
  610. + (NSDate *)dateFromDateString:(NSString *)dateString {
  611. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  612. NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
  613. return newDate;
  614. }
  615. + (NSString *)stringFromDateComponents:(NSDateComponents *)components {
  616. NSMutableString *rString = [NSMutableString new];
  617. if (components.year > 0) {
  618. [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
  619. }
  620. if (components.month > 0) {
  621. if (rString.length > 0) {
  622. [rString appendString:@" "];
  623. }
  624. [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
  625. }
  626. if (components.day > 0) {
  627. if (rString.length > 0) {
  628. [rString appendString:@" "];
  629. }
  630. [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
  631. }
  632. return rString;
  633. }
  634. + (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
  635. NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
  636. NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
  637. NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
  638. return rString;
  639. }
  640. + (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
  641. NSMutableString *rString = [NSMutableString new];
  642. if (components.year > 0) {
  643. [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
  644. }
  645. if (components.month > 0) {
  646. if (components.month < 10) {
  647. [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
  648. } else {
  649. [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
  650. }
  651. }
  652. return rString;
  653. }
  654. + (NSString *)paramMonthFromDateString:(NSString *)dateString {
  655. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  656. ds.day = 1;
  657. NSDateFormatter *df = [CommonUtil dateFormatter];
  658. df.dateFormat = @"YYYYMM";
  659. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  660. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  661. }
  662. + (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
  663. NSDateComponents *ds = [CommonUtil dateComponents:date];
  664. ds.day += day;
  665. NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
  666. return adjustDate;
  667. }
  668. //현재 로컬시간을 UTC로 변환합니다.
  669. + (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
  670. NSDateFormatter *df = [CommonUtil dateFormatter];
  671. [df setDateFormat:@"yyyyMMddHHmmss"];
  672. NSDate *locDate = [df dateFromString:locDateString];
  673. NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
  674. dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
  675. NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  676. [dfu setTimeZone:utc];
  677. NSString *timeStamp = [dfu stringFromDate:locDate];
  678. timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
  679. return timeStamp;
  680. }
  681. //UTC 시간을 현재 로컬 시간을 변환합니다.
  682. + (NSString *)localDateFromUTC:(NSString *)utcDateString {
  683. NSDateFormatter *df = [CommonUtil dateFormatter];
  684. [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
  685. NSDate *utcDate = [df dateFromString:utcDateString];
  686. NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
  687. [dfl setTimeZone:[NSTimeZone systemTimeZone]];
  688. [dfl setDateFormat:@"yyyyMMddHHmmss"];
  689. NSString* localString = [dfl stringFromDate:utcDate];
  690. return localString;
  691. }
  692. #pragma mark - TimeUtil
  693. + (NSString *)formattedTime:(NSString *)timeString {
  694. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  695. NSDateFormatter *df = [CommonUtil dateFormatter];
  696. df.dateFormat = @"HH시 mm분";
  697. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  698. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  699. }
  700. + (NSString *)formattedTime2:(NSString *)timeString {
  701. NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
  702. NSDateFormatter *df = [CommonUtil dateFormatter];
  703. df.dateFormat = @"HH시 mm분";
  704. NSString *period = ds.hour < 12 ? @"오전" : @"오후";
  705. if ([period isEqualToString:@"오후"]) {
  706. ds.hour -= 12;
  707. }
  708. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  709. return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
  710. }
  711. + (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
  712. NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
  713. if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
  714. NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
  715. NSString *hour = [timeArray firstObject];
  716. hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
  717. NSString *minute = [timeArray lastObject];
  718. minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
  719. dateComp.hour = [hour intValue];
  720. dateComp.minute = [minute intValue];
  721. } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
  722. NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
  723. if (timeArray && timeArray.count > 0) {
  724. dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
  725. dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
  726. }
  727. }
  728. return dateComp;
  729. }
  730. + (NSString *)stringFromTime:(NSDate *)date {
  731. NSDateFormatter *df = [CommonUtil dateFormatter];
  732. df.dateFormat = @"HH:mm";
  733. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  734. }
  735. #pragma mark - StringUtil
  736. + (NSNumberFormatter *)numberFormatter {
  737. static NSNumberFormatter *__shareNumberFormatter = nil;
  738. static dispatch_once_t onceToken;
  739. dispatch_once(&onceToken, ^{
  740. __shareNumberFormatter = [[NSNumberFormatter alloc] init];
  741. NSLocale *locale = [NSLocale currentLocale];
  742. [__shareNumberFormatter setLocale:locale];
  743. });
  744. return __shareNumberFormatter;
  745. }
  746. + (NSString *)numberString:(NSInteger)number {
  747. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  748. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  749. formatter.usesGroupingSeparator = YES;
  750. [formatter setGroupingSeparator:@","];
  751. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  752. return formattedString;
  753. }
  754. + (NSString *)currencyString:(NSInteger)number {
  755. NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
  756. if (number <= 0) {
  757. return currency;
  758. }
  759. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  760. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  761. formatter.usesGroupingSeparator = YES;
  762. [formatter setGroupingSeparator:@","];
  763. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  764. currency = [NSString stringWithFormat:@"%@ 원", formattedString];
  765. return currency;
  766. }
  767. + (NSString *)currencyString2:(NSInteger)number {
  768. NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
  769. if (number <= 0) {
  770. return currency;
  771. }
  772. NSNumberFormatter *formatter = [CommonUtil numberFormatter];
  773. formatter.numberStyle = NSNumberFormatterDecimalStyle;
  774. formatter.usesGroupingSeparator = YES;
  775. [formatter setGroupingSeparator:@","];
  776. NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
  777. currency = [NSString stringWithFormat:@"%@원", formattedString];
  778. return currency;
  779. }
  780. + (NSString *)svcNoString:(NSString *)svcNo {
  781. //0103333333
  782. NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
  783. if (svcNo.length == 10) {
  784. [tmpSvcNo insertString:@"-" atIndex:3];
  785. [tmpSvcNo insertString:@"-" atIndex:7];
  786. } else if (svcNo.length == 11) {
  787. [tmpSvcNo insertString:@"-" atIndex:3];
  788. [tmpSvcNo insertString:@"-" atIndex:8];
  789. }
  790. return tmpSvcNo;
  791. }
  792. + (NSString *)cutSaName:(NSString *)saName {
  793. NSRange range = [saName rangeOfString:@"]"];
  794. NSString *rSaName = nil;
  795. if (range.location != NSNotFound) {
  796. rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
  797. }
  798. return rSaName;
  799. }
  800. + (NSInteger)getIntegerFromCurrency:(NSString *)currency {
  801. NSInteger rvalue = 0;
  802. NSString *tmp = [NSString stringWithString:currency];
  803. NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
  804. if (fRange.location == currency.length-1) {
  805. tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
  806. }
  807. tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
  808. rvalue = [tmp intValue];
  809. return rvalue;
  810. }
  811. + (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
  812. if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
  813. return phoneNumber;
  814. }
  815. NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
  816. NSInteger lastIndex = phoneNumber.length - 3;
  817. [rString insertString:@"-" atIndex:3];
  818. [rString insertString:@"-" atIndex:lastIndex];
  819. return rString;
  820. }
  821. + (NSString *)formattedDate:(NSString *)dateString {
  822. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  823. NSDateFormatter *df = [CommonUtil dateFormatter];
  824. df.dateFormat = @"YYYY/MM/dd";
  825. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  826. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  827. }
  828. + (NSString *)formattedDate2:(NSString *)dateString {
  829. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  830. NSDateFormatter *df = [CommonUtil dateFormatter];
  831. df.dateFormat = @"YYYY.MM.dd";
  832. NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
  833. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  834. }
  835. + (NSString *)formattedMonthDate:(NSString *)dateString {
  836. NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
  837. NSDateFormatter *df = [CommonUtil dateFormatter];
  838. df.dateFormat = @"YYYY.MM";
  839. NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
  840. return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
  841. }
  842. + (NSString *)formattedIAId:(NSString *)iaId {
  843. NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
  844. [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
  845. return formatIAId;
  846. }
  847. + (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
  848. NSInteger count = 0, length = [occurString length];
  849. NSRange range = NSMakeRange(0, length);
  850. while(range.location != NSNotFound) {
  851. range = [occurString rangeOfString:occurString options:0 range:range];
  852. if(range.location != NSNotFound) {
  853. range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
  854. count++;
  855. }
  856. }
  857. return count;
  858. }
  859. +(NSString *)URLEncoding:(NSString *)sender{
  860. NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
  861. NULL,
  862. (CFStringRef)sender,
  863. NULL,
  864. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  865. kCFStringEncodingUTF8 ));
  866. return encodedString;
  867. }
  868. +(NSString *)URLDecoding:(NSString *)sender {
  869. // Decode a percent escape encoded string.
  870. NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
  871. (CFStringRef) sender,
  872. CFSTR(""),
  873. kCFStringEncodingUTF8));
  874. return decodeString;
  875. }
  876. #pragma resizableImageWithCapInsets
  877. +(UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)make resizingMode:(UIImageResizingMode)resizingMode img:(UIImage *)img{
  878. UIImage *image = nil;
  879. if (IOS_VERSION < 6.0f) {
  880. image = [img resizableImageWithCapInsets:make];
  881. } else {
  882. image = [img resizableImageWithCapInsets:make resizingMode:resizingMode];
  883. }
  884. return image;
  885. }
  886. #pragma getUrlPostUrl
  887. +(NSString *)switchPostUrl:(NSString *)getUrl{
  888. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  889. NSString *splturl = [urlLst objectAtIndex:1];
  890. return splturl;
  891. }
  892. +(NSString *)getUrl:(NSString *)getUrl{
  893. NSString *url;
  894. NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
  895. url = [urlLst objectAtIndex:0];
  896. return url;
  897. }
  898. + (BOOL)stringContainsEmoji:(NSString *)string {
  899. __block BOOL returnValue = NO;
  900. [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
  901. ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  902. const unichar hs = [substring characterAtIndex:0];
  903. // surrogate pair
  904. if (0xd800 <= hs && hs <= 0xdbff) {
  905. if (substring.length > 1) {
  906. const unichar ls = [substring characterAtIndex:1];
  907. const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
  908. if (0x1d000 <= uc && uc <= 0x1f77f) {
  909. returnValue = YES;
  910. }
  911. }
  912. } else if (substring.length > 1) {
  913. const unichar ls = [substring characterAtIndex:1];
  914. if (ls == 0x20e3) {
  915. returnValue = YES;
  916. }
  917. } else {
  918. // non surrogate
  919. if (0x2100 <= hs && hs <= 0x27ff) {
  920. returnValue = YES;
  921. } else if (0x2B05 <= hs && hs <= 0x2b07) {
  922. returnValue = YES;
  923. } else if (0x2934 <= hs && hs <= 0x2935) {
  924. returnValue = YES;
  925. } else if (0x3297 <= hs && hs <= 0x3299) {
  926. returnValue = YES;
  927. } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
  928. returnValue = YES;
  929. }
  930. }
  931. }];
  932. return returnValue;
  933. }
  934. #pragma mark - TimeZone Dictionary
  935. + (SortDictionary *)timeZoneDict {
  936. NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
  937. NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
  938. return [[SortDictionary alloc] initWithDictionary:dic];
  939. }
  940. @end