CommonUtil.m 45 KB

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