RAUtils.m 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  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. //+(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title
  507. //{
  508. // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  509. // [parent presentViewController:alertController animated:YES completion:nil];
  510. // return alertController;
  511. //
  512. //}
  513. +(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title completion:(void (^ __nullable)(void))completion
  514. {
  515. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  516. [parent presentViewController:alertController animated:YES completion:completion];
  517. NSLog(@"show waiting alert %p",alertController);
  518. return alertController;
  519. }
  520. +(void) playSound:(NSString*) name type:(NSString*) type
  521. {
  522. CFStringRef cfname = (__bridge CFStringRef)name;
  523. CFStringRef cftype = (__bridge CFStringRef)type;
  524. CFBundleRef mainBundle;
  525. SystemSoundID soundFileObject;
  526. mainBundle = CFBundleGetMainBundle ();
  527. CFURLRef soundFileURLRef = CFBundleCopyResourceURL (
  528. mainBundle,
  529. cfname,
  530. cftype,
  531. NULL
  532. );
  533. AudioServicesCreateSystemSoundID (
  534. soundFileURLRef,
  535. &soundFileObject
  536. );
  537. AudioServicesPlaySystemSound(soundFileObject);
  538. }
  539. +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  540. {
  541. if(title==nil)
  542. title = @"Message";
  543. if ([title isEqualToString:@"Add To Cart"]) {
  544. if ([msg hasPrefix:@"Out of Stock.\n"]) {
  545. title = @"Add To Cart: Out of Stock";
  546. msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  547. }
  548. }
  549. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  550. UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
  551. [alertController addAction:action_0];
  552. [vc presentViewController:alertController animated:YES completion:nil];
  553. NSLog(@"show message alert %p",alertController);
  554. return alertController;
  555. }
  556. +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc action_handler:(void (^ __nullable)(UIAlertAction *action))action_handler completion:(void (^ __nullable)(void))completion
  557. {
  558. if(title==nil)
  559. title = @"Message";
  560. if ([title isEqualToString:@"Add To Cart"]) {
  561. if ([msg hasPrefix:@"Out of Stock.\n"]) {
  562. title = @"Add To Cart: Out of Stock";
  563. msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  564. }
  565. }
  566. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  567. UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:action_handler];
  568. [alertController addAction:action_0];
  569. [vc presentViewController:alertController animated:YES completion:completion];
  570. NSLog(@"show message alert %p",alertController);
  571. return alertController;
  572. }
  573. //+(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
  574. //{
  575. // if(title==nil)
  576. // title = @"Please Wait";
  577. // if(msg==nil)
  578. // msg= @"Waiting...";
  579. // NSAssert(msg!=nil, @"error message from json is nil");
  580. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  581. // [alert show];
  582. // //
  583. // //
  584. // // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
  585. // // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  586. // // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
  587. // //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
  588. // //// [alert setValue:aiView forKey:@"accessoryView"];
  589. // //// }else{
  590. // //// [alert addSubview:aiView];
  591. // //// }
  592. // //
  593. // // aiView.hidden = false;
  594. // // aiView.hidesWhenStopped = false;
  595. // // [aiView startAnimating];
  596. // //
  597. // //[alert addSubview:aiView];
  598. //
  599. // return alert;
  600. // //return nil;
  601. // // return alert;
  602. // // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
  603. // //[alert show];
  604. //}
  605. +(NSDictionary*) device_info
  606. {
  607. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  608. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  609. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  610. NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
  611. NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
  612. [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  613. [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
  614. [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
  615. [info setValue:versionNum forKey:@"ver"];
  616. [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
  617. return info;
  618. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  619. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  620. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  621. }
  622. + (NSString *)deviceID {
  623. UIDevice * dev = [UIDevice currentDevice];
  624. NSUUID* uuid =dev.identifierForVendor;
  625. return uuid.UUIDString;
  626. }
  627. //+(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
  628. //{
  629. // NSArray *stringArray = [string componentsSeparatedByString:separator];
  630. //
  631. // return stringArray;
  632. //}
  633. +(NSDictionary*) string2dict:(NSString*) str
  634. {
  635. if(str==nil)
  636. return nil;
  637. NSError *error = nil;
  638. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
  639. options: NSJSONReadingMutableContainers
  640. error: &error];
  641. DebugLog(@"%@",string2dic);
  642. return string2dic;
  643. }
  644. +(UIColor*) strColor:(NSString*) color
  645. {
  646. if([color.lowercaseString isEqualToString:@"red"])
  647. return [UIColor redColor];
  648. return [UIColor blackColor];
  649. }
  650. +(NSString*) base64en:(NSString*) string
  651. {
  652. if(string == nil)
  653. return nil;
  654. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  655. NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
  656. return stringBase64;
  657. }
  658. +(NSString*) base64de:(NSString*) stringBase64
  659. {
  660. if(stringBase64==nil)
  661. return nil;
  662. NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
  663. NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  664. return string;
  665. }
  666. +(void) deletefiles :(NSString*) path
  667. {
  668. // NSString *extension = @"m4r";
  669. NSFileManager *fileManager = [NSFileManager defaultManager];
  670. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  671. // NSString *documentsDirectory = [paths objectAtIndex:0];
  672. NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
  673. NSEnumerator *e = [contents objectEnumerator];
  674. NSString *filename;
  675. while ((filename = [e nextObject])) {
  676. bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
  677. if(!result)
  678. DebugLog(@"delete file failed %@------%@",path,filename);
  679. }
  680. }
  681. +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
  682. {
  683. if(json==nil)
  684. return nil;
  685. NSMutableArray* ret = [[NSMutableArray alloc] init];
  686. int count = [[json valueForKey:count_fields] intValue];
  687. NSDictionary* items = nil;
  688. if(items_mark==nil)
  689. items = json;
  690. else
  691. items = [json objectForKey:items_mark];
  692. for(int i=0;i<count;i++)
  693. {
  694. NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
  695. [ret addObject:obj];
  696. }
  697. return ret;
  698. }
  699. +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
  700. {
  701. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  702. //#define RESULT_FALSE 0
  703. //#define RESULT_TRUE 2
  704. //#define RESULT_NET_ERROR -3
  705. //#define RESULT_NET_NOTAVAILABLE -4
  706. //#define RESULT_ERROR -5
  707. //#define RESULT_LOCALFILE_ERROR -7
  708. //#define RESULT_USERAUTH_ERROR -9
  709. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  710. //#define RESULT_SESSION_EXPIRED -13
  711. //#define RESULT_VER_LOW
  712. if(msg.length<=0)
  713. {
  714. switch (code) {
  715. case RESULT_NET_NOTAVAILABLE:
  716. msg= MSG_NET_NOTAVAILABLE;
  717. break;
  718. default:
  719. // assert(@"UNDEFINE ERROR CODE!");
  720. break;
  721. }
  722. }
  723. // if(code==RESULT_NET_NOTAVAILABLE)
  724. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  725. // else
  726. [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
  727. [ret setValue:msg forKey:@"err_msg"];
  728. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  729. // options:0
  730. // error:nil];
  731. return ret;
  732. }
  733. + (BOOL)isNumeric:(NSString*)string{
  734. NSScanner* scan = [NSScanner scannerWithString:string];
  735. int val;
  736. return[scan scanInt:&val] && [scan isAtEnd];
  737. }
  738. + (CGRect)relativeFrame:(CGRect) frame FromView:(UIView *)v toView:(UIView*)tv
  739. {
  740. return [v convertRect: frame toView:tv];
  741. }
  742. + (CGRect)relativeFrameForScreenWithView:(UIView *)v
  743. {
  744. UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
  745. CGRect rect=[v convertRect: v.bounds toView:window];
  746. return rect;
  747. // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
  748. //
  749. // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  750. // if (!iOS7) {
  751. // screenHeight -= 20;
  752. // }
  753. // UIView *view = v;
  754. // CGFloat x = .0;
  755. // CGFloat y = .0;
  756. // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
  757. // x += view.frame.origin.x;
  758. // y += view.frame.origin.y;
  759. // view = view.superview;
  760. // if ([view isKindOfClass:[UIScrollView class]]) {
  761. // x -= ((UIScrollView *) view).contentOffset.x;
  762. // y -= ((UIScrollView *) view).contentOffset.y;
  763. // }
  764. // }
  765. // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
  766. }
  767. + (BOOL)saveData:(NSData *)data toPath:(NSString *)path {
  768. // NSString *directory = [path stringByDeletingLastPathComponent];
  769. NSFileManager *manager = [NSFileManager defaultManager];
  770. NSString *dir = [path stringByDeletingLastPathComponent];
  771. BOOL create = [manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  772. if (create) {
  773. BOOL save = [manager createFileAtPath:path contents:data attributes:nil];
  774. if (save) {
  775. return YES;
  776. }
  777. return NO;
  778. }
  779. return NO;
  780. }
  781. + (void)removeFileAtPath:(NSString *)path {
  782. if (!path.length) {
  783. return;
  784. }
  785. NSFileManager *manager = [NSFileManager defaultManager];
  786. [manager removeItemAtPath:path error:nil];
  787. }
  788. + (NSString *)appCacheDirectory {
  789. return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  790. }
  791. +(NSString*)md5WithFile:(NSString*)path
  792. {
  793. return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
  794. }
  795. CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
  796. // Declare needed variables
  797. CFStringRef result = NULL;
  798. CFReadStreamRef readStream = NULL;
  799. // Get the file URL
  800. CFURLRef fileURL =
  801. CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
  802. (CFStringRef)filePath,
  803. kCFURLPOSIXPathStyle,
  804. (Boolean)false);
  805. if (!fileURL) goto done;
  806. // Create and open the read stream
  807. readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
  808. (CFURLRef)fileURL);
  809. if (!readStream) goto done;
  810. bool didSucceed = (bool)CFReadStreamOpen(readStream);
  811. if (!didSucceed) goto done;
  812. // Initialize the hash object
  813. CC_MD5_CTX hashObject;
  814. CC_MD5_Init(&hashObject);
  815. // Make sure chunkSizeForReadingData is valid
  816. if (!chunkSizeForReadingData) {
  817. chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
  818. }
  819. // Feed the data to the hash object
  820. bool hasMoreData = true;
  821. while (hasMoreData) {
  822. uint8_t buffer[chunkSizeForReadingData];
  823. CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
  824. if (readBytesCount == -1) break;
  825. if (readBytesCount == 0) {
  826. hasMoreData = false;
  827. continue;
  828. }
  829. CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
  830. }
  831. // Check if the read operation succeeded
  832. didSucceed = !hasMoreData;
  833. // Compute the hash digest
  834. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  835. CC_MD5_Final(digest, &hashObject);
  836. // Abort if the read operation failed
  837. if (!didSucceed) goto done;
  838. // Compute the string result
  839. char hash[2 * sizeof(digest) + 1];
  840. for (size_t i = 0; i < sizeof(digest); ++i) {
  841. snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
  842. }
  843. result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
  844. done:
  845. if (readStream) {
  846. CFReadStreamClose(readStream);
  847. CFRelease(readStream);
  848. }
  849. if (fileURL) {
  850. CFRelease(fileURL);
  851. }
  852. return result;
  853. }
  854. + (BOOL)fileExistsAtPath:(NSString *)path {
  855. NSFileManager *fm = [NSFileManager defaultManager];
  856. return [fm fileExistsAtPath:path];
  857. return NO;
  858. }
  859. + (NSString *)htmlForVideo:(NSString*) iframeCode template:(NSString*) path
  860. {
  861. if(path==nil)
  862. path=[[NSBundle mainBundle] pathForResource:@"photostack_video" ofType:@"html"];
  863. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  864. if(tempate==nil)
  865. return @"";
  866. // NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  867. // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  868. // imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  869. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:iframeCode];
  870. return tempate;
  871. }
  872. + (NSString *)htmlForImage:(UIImage *)image template:(NSString*) path
  873. {
  874. if(path==nil)
  875. path=[[NSBundle mainBundle] pathForResource:@"photostack_image" ofType:@"html"];
  876. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  877. if(tempate==nil)
  878. return @"";
  879. NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  880. // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  881. NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
  882. imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  883. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:imageSource];
  884. return tempate;
  885. }
  886. + (nullable NSString *)md5:(nullable NSString *)str {
  887. if (!str) return nil;
  888. const char *cStr = str.UTF8String;
  889. unsigned char result[CC_MD5_DIGEST_LENGTH];
  890. CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
  891. NSMutableString *md5Str = [NSMutableString string];
  892. for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
  893. [md5Str appendFormat:@"%02x", result[i]];
  894. }
  895. return md5Str;
  896. }
  897. + (void)ra_showAlertTitle:(NSString *)title message:(NSString *)msg withViewController:(UIViewController *)vc {
  898. if (vc) {
  899. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
  900. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  901. }];
  902. [alertVC addAction:okAction];
  903. [vc presentViewController:alertVC animated:YES completion:nil];
  904. NSLog(@"show alerttitle alert %p",alertVC);
  905. }
  906. }
  907. + (CGSize)sizeWithFont:(NSString*)string font:(UIFont *)font constrainedToSize:(CGSize)maxsize lineBreakMode:(NSLineBreakMode)lineBreakMode
  908. {
  909. if(string.length==0)
  910. return CGSizeZero;
  911. // Let's make an NSAttributedString first
  912. NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
  913. //Add LineBreakMode
  914. NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
  915. [paragraphStyle setLineBreakMode:lineBreakMode];
  916. [attributedString setAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, attributedString.length)];
  917. // Add Font
  918. [attributedString setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, attributedString.length)];
  919. //Now let's make the Bounding Rect
  920. CGSize expectedSize = [attributedString boundingRectWithSize:maxsize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
  921. return expectedSize;
  922. }
  923. + (BOOL) validateEmail:(NSString *)email
  924. {
  925. NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
  926. NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
  927. NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
  928. NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
  929. return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
  930. }
  931. + (BOOL)checkPassword:(NSString *) password
  932. {
  933. NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,16}";
  934. // NSString *pattern1 = @"^(?=.*)(?=.*[a-z])(?=.*[~!@#$%^&*:;,.=?$\x22]).{8,16}$";
  935. NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  936. // NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern1];
  937. BOOL isMatch = [pred evaluateWithObject:password];//||[pred evaluateWithObject:password];
  938. return isMatch;
  939. }
  940. + (UIViewController *)getCurrentVC
  941. {
  942. UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
  943. UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
  944. return currentVC;
  945. }
  946. + (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
  947. {
  948. UIViewController *currentVC;
  949. if ([rootVC presentedViewController]) {
  950. // 视图是被presented出来的
  951. rootVC = [rootVC presentedViewController];
  952. }
  953. if ([rootVC isKindOfClass:[UITabBarController class]]) {
  954. // 根视图为UITabBarController
  955. currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
  956. } else if ([rootVC isKindOfClass:[UINavigationController class]]){
  957. // 根视图为UINavigationController
  958. currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
  959. } else {
  960. // 根视图为非导航类
  961. currentVC = rootVC;
  962. }
  963. return currentVC;
  964. }
  965. @end