RAUtils.m 42 KB

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