RAUtils.m 32 KB

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