RAUtils.m 38 KB

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