RAUtils.m 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. //
  2. // RAUtils.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 9/17/15.
  6. // Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "RAUtils.h"
  9. #import "RAConvertor.h"
  10. #import "const.h"
  11. //#import "LoginViewController.h"
  12. //#import "MainViewController.h"
  13. #import <sys/param.h>
  14. #import <sys/mount.h>
  15. //#import "const.h"
  16. #import "AppDelegate.h"
  17. //#import "Singleton.h"
  18. #include <CommonCrypto/CommonDigest.h>
  19. //#import "ZipArchive.h"
  20. #define FileHashDefaultChunkSizeForReadingData 1024*8
  21. @implementation RAUtils
  22. +(int)getRandomNumber:(int)from to:(int)to
  23. {
  24. return (int)(from + (arc4random() % (to-from + 1)));
  25. }
  26. //+(float)randomf
  27. //{
  28. //
  29. // int irandom = [self getRandomNumber:0 to:5];
  30. // return irandom / 100.0;
  31. //}
  32. +(NSData*) getdbfile:(NSString*)dbname
  33. {
  34. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  35. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  36. NSString *database_path = [documents stringByAppendingPathComponent:dbname];
  37. return [NSData dataWithContentsOfFile:database_path];
  38. }
  39. +(NSDictionary*) dictfromfile:(NSString*) path
  40. {
  41. NSData *filedata = [NSData dataWithContentsOfFile:path];
  42. if(filedata == nil)
  43. return nil;
  44. NSError *error = nil;
  45. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
  46. options: NSJSONReadingMutableContainers
  47. error: &error];
  48. // DebugLog(@"%@",string2dic);
  49. return string2dic;
  50. }
  51. +(void) dicttofile:(NSString*) path dict:(NSDictionary*)dict
  52. {
  53. NSDictionary* saveddict = dict;
  54. if(saveddict==nil)
  55. return;
  56. NSString *filestr =[RAConvertor dict2string:dict];
  57. NSError *error=nil;
  58. [filestr writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:&error];
  59. // DebugLog(@"%@",string2dic);
  60. // return string2dic;
  61. }
  62. + (NSArray*) allFilesAtPath:(NSString*) dirString
  63. {
  64. NSMutableArray* array = [NSMutableArray arrayWithCapacity:10];
  65. NSFileManager* fileMgr = [NSFileManager defaultManager];
  66. NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:dirString error:nil];
  67. for (NSString* fileName in tempArray) {
  68. BOOL flag = YES;
  69. NSString* fullPath = [dirString stringByAppendingPathComponent:fileName];
  70. if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
  71. if (!flag) {
  72. [array addObject:fullPath];
  73. }
  74. }
  75. }
  76. return array;
  77. }
  78. + (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {
  79. DebugLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);
  80. NSFileManager *fm = [NSFileManager defaultManager];
  81. NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
  82. NSString *subPath;
  83. while ((subPath = [srcDirEnum nextObject])) {
  84. DebugLog(@" subPath: %@", subPath);
  85. NSString *srcFullPath = [srcDir stringByAppendingPathComponent:subPath];
  86. NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];
  87. // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
  88. BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
  89. // Create directory, or delete existing file and move file to destination
  90. if (isDirectory) {
  91. DebugLog(@" create directory");
  92. [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
  93. if (err && *err) {
  94. DebugLog(@"ERROR: %@", *err);
  95. return false;
  96. }
  97. }
  98. else {
  99. if ([fm fileExistsAtPath:potentialDstPath]) {
  100. DebugLog(@" removeItemAtPath");
  101. [fm removeItemAtPath:potentialDstPath error:err];
  102. if (err && *err) {
  103. DebugLog(@"ERROR: %@", *err);
  104. return false;
  105. }
  106. }
  107. DebugLog(@" moveItemAtPath");
  108. [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
  109. if (err && *err) {
  110. DebugLog(@"ERROR: %@", *err);
  111. return false;
  112. }
  113. }
  114. }
  115. [fm removeItemAtPath:srcDir error:err];
  116. if (err && *err) {
  117. DebugLog(@"ERROR: %@", *err);
  118. return false;
  119. }
  120. return true;
  121. }
  122. //+(void) enum_font
  123. //{
  124. // return;
  125. // NSArray *familys = [UIFont familyNames];
  126. //
  127. // for (int i = 0; i < familys.count; i++)
  128. // {
  129. // NSString *family = [familys objectAtIndex:i];
  130. // DebugLog(@"=====Fontfamily:%@", family);
  131. // NSArray *fonts = [UIFont fontNamesForFamilyName:family];
  132. // for(int j = 0; j < fonts.count; j++)
  133. // {
  134. // DebugLog(@"***FontName:%@", [fonts objectAtIndex:j]);
  135. // }
  136. // }
  137. //}
  138. //+(NSTextCheckingResult*) expression_findfistMatch:(NSString*)content regex:(NSString*) pattern
  139. //{
  140. // NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
  141. //
  142. // NSTextCheckingResult *match = [regex firstMatchInString:content options:0 range:NSMakeRange(0, content.length)];
  143. // return match;
  144. //// if (matches) {
  145. //// for (NSTextCheckingResult *match in matches) {
  146. //// for (int i = 0; i < match.numberOfRanges; ++i) {
  147. //// DebugLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
  148. //// }
  149. //// }
  150. //// }
  151. //// return matches;
  152. //}
  153. //+(NSArray*) expression_varable:(NSString*)content regex:(NSString*) pattern
  154. //{
  155. //
  156. // if(content==nil)
  157. // return nil;
  158. //
  159. //
  160. // NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
  161. //
  162. // NSArray *matches = [regex matchesInString:content options:0 range:NSMakeRange(0, content.length)];
  163. //
  164. // if (matches) {
  165. // for (NSTextCheckingResult *match in matches) {
  166. // for (int i = 0; i < match.numberOfRanges; ++i) {
  167. // DebugLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
  168. // }
  169. // }
  170. // }
  171. // return matches;
  172. //}
  173. + (CGRect)rectAlign:(CGRect )parent rect:(CGRect)rect hAlign:(NSString*)hAlign vAlign:(NSString*)vAlign
  174. {
  175. // double cx=parent.origin.x+parent.size.width/2;
  176. // double cy=parent.origin.y+parent.size.height/2;
  177. CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
  178. if([hAlign.lowercaseString isEqualToString:@"center"])
  179. {
  180. rect=CGRectMake(centerpoint.x-rect.size.width/2, rect.origin.y, rect.size.width, rect.size.height);
  181. }
  182. else
  183. if([hAlign.lowercaseString isEqualToString:@"left"])
  184. {
  185. rect=CGRectMake(parent.origin.x, rect.origin.y, rect.size.width, rect.size.height);
  186. }
  187. else
  188. if([hAlign.lowercaseString isEqualToString:@"right"])
  189. {
  190. rect=CGRectMake(parent.origin.x+parent.size.width-rect.size.width, rect.origin.y, rect.size.width, rect.size.height);
  191. }
  192. if([vAlign.lowercaseString isEqualToString:@"middle"])
  193. {
  194. rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
  195. }
  196. return rect;
  197. }
  198. +(NSString*) get_config_path
  199. {
  200. NSString *default_path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
  201. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  202. NSString *cache_folder=[paths objectAtIndex:0];
  203. NSString* ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
  204. NSString *config_path = [cache_folder stringByAppendingPathComponent:[NSString stringWithFormat: @"config_%@.plist",ver]];
  205. BOOL bdir=NO;
  206. NSFileManager* fileManager = [NSFileManager defaultManager];
  207. if(! [fileManager fileExistsAtPath:config_path isDirectory:&bdir])
  208. {
  209. NSError * error=nil;
  210. if(![fileManager copyItemAtPath:default_path toPath:config_path error:&error])
  211. {
  212. return nil;
  213. }
  214. }
  215. return config_path;
  216. }
  217. + (CGRect)rectVAlign:(CGRect )parent rect:(CGRect)rect vAlign:(NSString*)vAlign
  218. {
  219. // double cx=parent.origin.x+parent.size.width/2;
  220. // double cy=parent.origin.y+parent.size.height/2;
  221. CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
  222. if([vAlign.lowercaseString isEqualToString:@"middle"])
  223. {
  224. rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
  225. }
  226. return rect;
  227. }
  228. + (CGRect)scaleToSize:(CGRect )from to:(CGSize)to
  229. {
  230. if(from.size.width/from.size.height>to.width/to.height)
  231. {
  232. return CGRectMake(from.origin.x, from.origin.y, to.width, to.width*from.size.height/from.size.width);
  233. }
  234. else
  235. {
  236. return CGRectMake(from.origin.x, from.origin.y, to.height*from.size.width/from.size.height, to.height);
  237. }
  238. // // 创建一个bitmap的context
  239. // // 并把它设置成为当前正在使用的context
  240. // UIGraphicsBeginImageContext(size);
  241. // // 绘制改变大小的图片
  242. // [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
  243. // // 从当前context中创建一个改变大小后的图片
  244. // UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  245. // // 使当前的context出堆栈
  246. // UIGraphicsEndImageContext();
  247. // // 返回新的改变大小后的图片
  248. //
  249. // // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
  250. // return scaledImage;
  251. }
  252. + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
  253. // 创建一个bitmap的context
  254. // 并把它设置成为当前正在使用的context
  255. UIGraphicsBeginImageContext(size);
  256. // 绘制改变大小的图片
  257. [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
  258. // 从当前context中创建一个改变大小后的图片
  259. UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  260. // 使当前的context出堆栈
  261. UIGraphicsEndImageContext();
  262. // 返回新的改变大小后的图片
  263. // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
  264. return scaledImage;
  265. }
  266. +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size
  267. {
  268. //UIImage *image=[UIImage imageNamed:@"xxoo.jpeg"];
  269. NSData *imageData=UIImageJPEGRepresentation(image, 1.f);
  270. if(size>imageData.length/1024)
  271. return image;
  272. // CGFloat size=40.f;// kb
  273. CGFloat scale=size/(imageData.length/1024);
  274. scale = sqrt (scale);
  275. CGSize newsize=image.size;
  276. newsize.height = newsize.height*scale;
  277. newsize.width = newsize.width*scale;
  278. return [RAUtils scaleToSize:image size:newsize];
  279. // NSData *newData=UIImageJPEGRepresentation(image, scale);
  280. // UIImage* ret= [[UIImage alloc] initWithData:newData];
  281. //
  282. // return ret;
  283. }
  284. +(NSString*) FloatFormat:(float)value
  285. {
  286. if (fmodf(value, 1)==0)
  287. {
  288. return [NSString stringWithFormat:@"%.0f",value];
  289. } else if (fmodf(value*10, 1)==0)
  290. {
  291. return [NSString stringWithFormat:@"%.1f",value];
  292. }
  293. else if (fmodf(value*100, 1)==0)
  294. {
  295. return [NSString stringWithFormat:@"%.2f",value];
  296. }
  297. else if (fmodf(value*1000, 1)==0)
  298. {
  299. return [NSString stringWithFormat:@"%.3f",value];
  300. }
  301. else
  302. {
  303. return [NSString stringWithFormat:@"%.4f",value];
  304. }
  305. return nil;
  306. }
  307. +(UIViewController*) getViewController:(UIView*) view
  308. {
  309. for (UIView* next = [view superview]; next; next = next.superview) {
  310. UIResponder* nextResponder = [next nextResponder];
  311. if ([nextResponder isKindOfClass:[UIViewController class]]) {
  312. return (UIViewController*)nextResponder;
  313. }
  314. }
  315. return nil;
  316. }
  317. + (float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
  318. {
  319. NSFileManager *fileManager = [[NSFileManager alloc] init];
  320. float size =0;
  321. NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
  322. for(int i = 0; i<[array count]; i++)
  323. {
  324. NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
  325. BOOL isDir;
  326. if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
  327. {
  328. NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
  329. size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
  330. }
  331. else
  332. {
  333. size+=[self fileSizeForDir:fullPath];
  334. }
  335. }
  336. return size;
  337. }
  338. /*创建错误信息字典*/
  339. +(NSDictionary*) error_dict:(NSError*)error
  340. {
  341. if(error==nil)
  342. return nil;
  343. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  344. [ret setValue:[NSString stringWithFormat:@"%ld",(long)error.code] forKey:@"error_code"];
  345. [ret setValue:error.domain forKey:@"err_domain"];
  346. [ret setValue:[error localizedDescription] forKey:@"err_message"];
  347. // [ret setObject:error.userInfo forKey:@"user_info"];
  348. return ret;
  349. }
  350. +(NSString*) current_date
  351. {
  352. NSDate * date = [NSDate date];
  353. NSTimeInterval sec = [date timeIntervalSinceNow];
  354. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  355. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  356. [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  357. NSString * na = [df stringFromDate:currentDate];
  358. return na;
  359. }
  360. +(NSString*) current_date_time
  361. {
  362. NSDate * date = [NSDate date];
  363. NSTimeInterval sec = [date timeIntervalSinceNow];
  364. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  365. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  366. [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  367. NSString * na = [df stringFromDate:currentDate];
  368. return na;
  369. }
  370. +(NSString*) current_date_forfile
  371. {
  372. NSDate * date = [NSDate date];
  373. NSTimeInterval sec = [date timeIntervalSinceNow];
  374. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  375. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  376. [df setDateFormat:@"MM_dd_yyyy_HH_mm_ss"];
  377. NSString * na = [df stringFromDate:currentDate];
  378. return na;
  379. }
  380. //+(void) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  381. //{
  382. // if(title==nil)
  383. // title = @"Message";
  384. // if ([title isEqualToString:@"Add To Cart"]) {
  385. // if ([msg hasPrefix:@"Out of Stock.\n"]) {
  386. // title = @"Add To Cart: Out of Stock";
  387. // msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  388. // }
  389. // }
  390. //
  391. //
  392. //
  393. // return [self alert_view:msg title:title];
  394. ////
  395. ////
  396. //// UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
  397. //// //block代码块取代了delegate
  398. ////
  399. ////
  400. //// // [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  401. //// // textField.text = self.save_name;
  402. //// //
  403. //// //
  404. //// // }];
  405. ////
  406. //// // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  407. //// //
  408. //// // UIAlertController * waitalert = [RAUtils waiting_alert:self title:@"Delete Order"];
  409. //// // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  410. //// //
  411. //// // NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
  412. //// //
  413. //// // dispatch_async(dispatch_get_main_queue(), ^{
  414. //// // [waitalert dismissViewControllerAnimated:YES completion:nil];
  415. //// //
  416. //// //
  417. //// // if([[return_json valueForKey:@"result"] intValue]==2)
  418. //// // {
  419. //// //
  420. //// // [RAUtils error_alert:nil title:@"Order Delete"] ;
  421. //// // }
  422. //// // else
  423. //// // {
  424. //// // [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
  425. //// // }
  426. //// //
  427. //// //
  428. //// //
  429. //// //
  430. //// // });
  431. //// // });
  432. //// //
  433. //// //
  434. //// // }];
  435. ////
  436. //// UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  437. //// //DebugLog(@"Cancel");
  438. //// }];
  439. //// // [alertControl addAction:actionOne];
  440. ////
  441. //// [alertControl addAction:alertthree];
  442. ////
  443. ////
  444. //// UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  445. //// }];
  446. //// [alertControl addAction:alertcancel];
  447. //// //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  448. ////
  449. ////
  450. ////
  451. ////
  452. //// [vc presentViewController:alertControl animated:YES completion:nil];
  453. ////
  454. ////
  455. ////
  456. //// return;
  457. ////
  458. ////
  459. //
  460. //
  461. //}
  462. //+(void) alert_view :(NSString*) msg title:(NSString*) title
  463. //{
  464. // if(title==nil)
  465. // title = NSLocalizedString(@"Message", @"Message");
  466. // if(msg.length>0)
  467. // {
  468. // title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
  469. // }
  470. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", @"Ok") otherButtonTitles:nil, nil];
  471. // [alert show];
  472. //}
  473. + (long long) freeDiskSpaceInMegaBytes{
  474. struct statfs buf;
  475. long long freespace = -1;
  476. if(statfs("/var", &buf) >= 0){
  477. freespace = (long long)(buf.f_bsize * buf.f_bfree);
  478. }
  479. DebugLog(@"手机剩余存储空间为:%qi MB" ,freespace/1024/1024);
  480. return freespace/1024/1024;
  481. }
  482. //+(UIAlertController*) waiting_alert:(UIViewController*)parent title:(NSString*) title
  483. //{
  484. // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
  485. //
  486. //// [parent presentModalViewController:alertController animated:YES];
  487. // [parent presentViewController:alertController animated:YES completion:nil];
  488. // return alertController;
  489. //
  490. //}
  491. +(UIAlertController*) waiting_alert:(UIViewController*)parent title:(NSString*) title completion:(void (^ __nullable)(void))completion
  492. {
  493. return [self waiting_alert:parent message:@"Please wait..." title:title completion:completion];
  494. // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
  495. //
  496. // [parent presentViewController:alertController animated:YES completion:completion];
  497. // return alertController;
  498. }
  499. //+(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title
  500. //{
  501. // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  502. // [parent presentViewController:alertController animated:YES completion:nil];
  503. // return alertController;
  504. //
  505. //}
  506. +(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title completion:(void (^ __nullable)(void))completion
  507. {
  508. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  509. [parent presentViewController:alertController animated:YES completion:completion];
  510. NSLog(@"show waiting alert %p",alertController);
  511. return alertController;
  512. }
  513. +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  514. {
  515. if(title==nil)
  516. title = @"Message";
  517. if ([title isEqualToString:@"Add To Cart"]) {
  518. if ([msg hasPrefix:@"Out of Stock.\n"]) {
  519. title = @"Add To Cart: Out of Stock";
  520. msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  521. }
  522. }
  523. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  524. UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
  525. [alertController addAction:action_0];
  526. [vc presentViewController:alertController animated:YES completion:nil];
  527. NSLog(@"show message alert %p",alertController);
  528. return alertController;
  529. }
  530. +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc action_handler:(void (^ __nullable)(UIAlertAction *action))action_handler completion:(void (^ __nullable)(void))completion
  531. {
  532. if(title==nil)
  533. title = @"Message";
  534. if ([title isEqualToString:@"Add To Cart"]) {
  535. if ([msg hasPrefix:@"Out of Stock.\n"]) {
  536. title = @"Add To Cart: Out of Stock";
  537. msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  538. }
  539. }
  540. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  541. UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:action_handler];
  542. [alertController addAction:action_0];
  543. [vc presentViewController:alertController animated:YES completion:completion];
  544. NSLog(@"show message alert %p",alertController);
  545. return alertController;
  546. }
  547. //+(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
  548. //{
  549. // if(title==nil)
  550. // title = @"Please Wait";
  551. // if(msg==nil)
  552. // msg= @"Waiting...";
  553. // NSAssert(msg!=nil, @"error message from json is nil");
  554. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  555. // [alert show];
  556. // //
  557. // //
  558. // // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
  559. // // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  560. // // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
  561. // //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
  562. // //// [alert setValue:aiView forKey:@"accessoryView"];
  563. // //// }else{
  564. // //// [alert addSubview:aiView];
  565. // //// }
  566. // //
  567. // // aiView.hidden = false;
  568. // // aiView.hidesWhenStopped = false;
  569. // // [aiView startAnimating];
  570. // //
  571. // //[alert addSubview:aiView];
  572. //
  573. // return alert;
  574. // //return nil;
  575. // // return alert;
  576. // // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
  577. // //[alert show];
  578. //}
  579. +(NSDictionary*) device_info
  580. {
  581. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  582. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  583. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  584. NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
  585. NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
  586. [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  587. [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
  588. [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
  589. [info setValue:versionNum forKey:@"ver"];
  590. [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
  591. return info;
  592. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  593. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  594. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  595. }
  596. + (NSString *)deviceID {
  597. UIDevice * dev = [UIDevice currentDevice];
  598. NSUUID* uuid =dev.identifierForVendor;
  599. return uuid.UUIDString;
  600. }
  601. //+(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
  602. //{
  603. // NSArray *stringArray = [string componentsSeparatedByString:separator];
  604. //
  605. // return stringArray;
  606. //}
  607. +(NSDictionary*) string2dict:(NSString*) str
  608. {
  609. if(str==nil)
  610. return nil;
  611. NSError *error = nil;
  612. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
  613. options: NSJSONReadingMutableContainers
  614. error: &error];
  615. DebugLog(@"%@",string2dic);
  616. return string2dic;
  617. }
  618. +(UIColor*) strColor:(NSString*) color
  619. {
  620. if([color.lowercaseString isEqualToString:@"red"])
  621. return [UIColor redColor];
  622. return [UIColor blackColor];
  623. }
  624. +(NSString*) base64en:(NSString*) string
  625. {
  626. if(string == nil)
  627. return nil;
  628. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  629. NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
  630. return stringBase64;
  631. }
  632. +(NSString*) base64de:(NSString*) stringBase64
  633. {
  634. if(stringBase64==nil)
  635. return nil;
  636. NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
  637. NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  638. return string;
  639. }
  640. +(void) deletefiles :(NSString*) path
  641. {
  642. // NSString *extension = @"m4r";
  643. NSFileManager *fileManager = [NSFileManager defaultManager];
  644. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  645. // NSString *documentsDirectory = [paths objectAtIndex:0];
  646. NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
  647. NSEnumerator *e = [contents objectEnumerator];
  648. NSString *filename;
  649. while ((filename = [e nextObject])) {
  650. bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
  651. if(!result)
  652. DebugLog(@"delete file failed %@------%@",path,filename);
  653. }
  654. }
  655. +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
  656. {
  657. if(json==nil)
  658. return nil;
  659. NSMutableArray* ret = [[NSMutableArray alloc] init];
  660. int count = [[json valueForKey:count_fields] intValue];
  661. NSDictionary* items = nil;
  662. if(items_mark==nil)
  663. items = json;
  664. else
  665. items = [json objectForKey:items_mark];
  666. for(int i=0;i<count;i++)
  667. {
  668. NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
  669. [ret addObject:obj];
  670. }
  671. return ret;
  672. }
  673. +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
  674. {
  675. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  676. //#define RESULT_FALSE 0
  677. //#define RESULT_TRUE 2
  678. //#define RESULT_NET_ERROR -3
  679. //#define RESULT_NET_NOTAVAILABLE -4
  680. //#define RESULT_ERROR -5
  681. //#define RESULT_LOCALFILE_ERROR -7
  682. //#define RESULT_USERAUTH_ERROR -9
  683. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  684. //#define RESULT_SESSION_EXPIRED -13
  685. //#define RESULT_VER_LOW
  686. if(msg.length<=0)
  687. {
  688. switch (code) {
  689. case RESULT_NET_NOTAVAILABLE:
  690. msg= MSG_NET_NOTAVAILABLE;
  691. break;
  692. default:
  693. // assert(@"UNDEFINE ERROR CODE!");
  694. break;
  695. }
  696. }
  697. // if(code==RESULT_NET_NOTAVAILABLE)
  698. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  699. // else
  700. [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
  701. [ret setValue:msg forKey:@"err_msg"];
  702. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  703. // options:0
  704. // error:nil];
  705. return ret;
  706. }
  707. + (BOOL)isNumeric:(NSString*)string{
  708. NSScanner* scan = [NSScanner scannerWithString:string];
  709. int val;
  710. return[scan scanInt:&val] && [scan isAtEnd];
  711. }
  712. + (CGRect)relativeFrame:(CGRect) frame FromView:(UIView *)v toView:(UIView*)tv
  713. {
  714. return [v convertRect: frame toView:tv];
  715. }
  716. + (CGRect)relativeFrameForScreenWithView:(UIView *)v
  717. {
  718. UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
  719. CGRect rect=[v convertRect: v.bounds toView:window];
  720. return rect;
  721. // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
  722. //
  723. // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  724. // if (!iOS7) {
  725. // screenHeight -= 20;
  726. // }
  727. // UIView *view = v;
  728. // CGFloat x = .0;
  729. // CGFloat y = .0;
  730. // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
  731. // x += view.frame.origin.x;
  732. // y += view.frame.origin.y;
  733. // view = view.superview;
  734. // if ([view isKindOfClass:[UIScrollView class]]) {
  735. // x -= ((UIScrollView *) view).contentOffset.x;
  736. // y -= ((UIScrollView *) view).contentOffset.y;
  737. // }
  738. // }
  739. // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
  740. }
  741. + (BOOL)saveData:(NSData *)data toPath:(NSString *)path {
  742. // NSString *directory = [path stringByDeletingLastPathComponent];
  743. NSFileManager *manager = [NSFileManager defaultManager];
  744. NSString *dir = [path stringByDeletingLastPathComponent];
  745. BOOL create = [manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  746. if (create) {
  747. BOOL save = [manager createFileAtPath:path contents:data attributes:nil];
  748. if (save) {
  749. return YES;
  750. }
  751. return NO;
  752. }
  753. return NO;
  754. }
  755. + (void)removeFileAtPath:(NSString *)path {
  756. if (!path.length) {
  757. return;
  758. }
  759. NSFileManager *manager = [NSFileManager defaultManager];
  760. [manager removeItemAtPath:path error:nil];
  761. }
  762. + (NSString *)appCacheDirectory {
  763. return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  764. }
  765. +(NSString*)md5WithFile:(NSString*)path
  766. {
  767. return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
  768. }
  769. CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
  770. // Declare needed variables
  771. CFStringRef result = NULL;
  772. CFReadStreamRef readStream = NULL;
  773. // Get the file URL
  774. CFURLRef fileURL =
  775. CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
  776. (CFStringRef)filePath,
  777. kCFURLPOSIXPathStyle,
  778. (Boolean)false);
  779. if (!fileURL) goto done;
  780. // Create and open the read stream
  781. readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
  782. (CFURLRef)fileURL);
  783. if (!readStream) goto done;
  784. bool didSucceed = (bool)CFReadStreamOpen(readStream);
  785. if (!didSucceed) goto done;
  786. // Initialize the hash object
  787. CC_MD5_CTX hashObject;
  788. CC_MD5_Init(&hashObject);
  789. // Make sure chunkSizeForReadingData is valid
  790. if (!chunkSizeForReadingData) {
  791. chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
  792. }
  793. // Feed the data to the hash object
  794. bool hasMoreData = true;
  795. while (hasMoreData) {
  796. uint8_t buffer[chunkSizeForReadingData];
  797. CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
  798. if (readBytesCount == -1) break;
  799. if (readBytesCount == 0) {
  800. hasMoreData = false;
  801. continue;
  802. }
  803. CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
  804. }
  805. // Check if the read operation succeeded
  806. didSucceed = !hasMoreData;
  807. // Compute the hash digest
  808. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  809. CC_MD5_Final(digest, &hashObject);
  810. // Abort if the read operation failed
  811. if (!didSucceed) goto done;
  812. // Compute the string result
  813. char hash[2 * sizeof(digest) + 1];
  814. for (size_t i = 0; i < sizeof(digest); ++i) {
  815. snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
  816. }
  817. result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
  818. done:
  819. if (readStream) {
  820. CFReadStreamClose(readStream);
  821. CFRelease(readStream);
  822. }
  823. if (fileURL) {
  824. CFRelease(fileURL);
  825. }
  826. return result;
  827. }
  828. + (BOOL)fileExistsAtPath:(NSString *)path {
  829. NSFileManager *fm = [NSFileManager defaultManager];
  830. return [fm fileExistsAtPath:path];
  831. return NO;
  832. }
  833. + (NSString *)htmlForVideo:(NSString*) iframeCode template:(NSString*) path
  834. {
  835. if(path==nil)
  836. path=[[NSBundle mainBundle] pathForResource:@"photostack_video" ofType:@"html"];
  837. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  838. if(tempate==nil)
  839. return @"";
  840. // NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  841. // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  842. // imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  843. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:iframeCode];
  844. return tempate;
  845. }
  846. + (NSString *)htmlForImage:(UIImage *)image template:(NSString*) path
  847. {
  848. if(path==nil)
  849. path=[[NSBundle mainBundle] pathForResource:@"photostack_image" ofType:@"html"];
  850. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  851. if(tempate==nil)
  852. return @"";
  853. NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  854. // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  855. NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
  856. imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  857. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:imageSource];
  858. return tempate;
  859. }
  860. + (nullable NSString *)md5:(nullable NSString *)str {
  861. if (!str) return nil;
  862. const char *cStr = str.UTF8String;
  863. unsigned char result[CC_MD5_DIGEST_LENGTH];
  864. CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
  865. NSMutableString *md5Str = [NSMutableString string];
  866. for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
  867. [md5Str appendFormat:@"%02x", result[i]];
  868. }
  869. return md5Str;
  870. }
  871. + (void)ra_showAlertTitle:(NSString *)title message:(NSString *)msg withViewController:(UIViewController *)vc {
  872. if (vc) {
  873. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  874. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  875. }];
  876. [alertVC addAction:okAction];
  877. [vc presentViewController:alertVC animated:YES completion:nil];
  878. NSLog(@"show alerttitle alert %p",alertVC);
  879. }
  880. }
  881. + (CGSize)sizeWithFont:(NSString*)string font:(UIFont *)font constrainedToSize:(CGSize)maxsize lineBreakMode:(NSLineBreakMode)lineBreakMode
  882. {
  883. if(string.length==0)
  884. return CGSizeZero;
  885. // Let's make an NSAttributedString first
  886. NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
  887. //Add LineBreakMode
  888. NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
  889. [paragraphStyle setLineBreakMode:lineBreakMode];
  890. [attributedString setAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, attributedString.length)];
  891. // Add Font
  892. [attributedString setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, attributedString.length)];
  893. //Now let's make the Bounding Rect
  894. CGSize expectedSize = [attributedString boundingRectWithSize:maxsize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
  895. return expectedSize;
  896. }
  897. + (BOOL) validateEmail:(NSString *)email
  898. {
  899. NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
  900. NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
  901. NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
  902. NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
  903. return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
  904. }
  905. + (BOOL)checkPassword:(NSString *) password
  906. {
  907. NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,16}";
  908. // NSString *pattern1 = @"^(?=.*)(?=.*[a-z])(?=.*[~!@#$%^&*:;,.=?$\x22]).{8,16}$";
  909. NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  910. // NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern1];
  911. BOOL isMatch = [pred evaluateWithObject:password];//||[pred evaluateWithObject:password];
  912. return isMatch;
  913. }
  914. + (UIViewController *)getCurrentVC
  915. {
  916. UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
  917. UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
  918. return currentVC;
  919. }
  920. + (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
  921. {
  922. UIViewController *currentVC;
  923. if ([rootVC presentedViewController]) {
  924. // 视图是被presented出来的
  925. rootVC = [rootVC presentedViewController];
  926. }
  927. if ([rootVC isKindOfClass:[UITabBarController class]]) {
  928. // 根视图为UITabBarController
  929. currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
  930. } else if ([rootVC isKindOfClass:[UINavigationController class]]){
  931. // 根视图为UINavigationController
  932. currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
  933. } else {
  934. // 根视图为非导航类
  935. currentVC = rootVC;
  936. }
  937. return currentVC;
  938. }
  939. @end