RAUtils.m 39 KB

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