RAUtils.m 32 KB

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