RAUtils.m 29 KB

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