RAUtils.m 31 KB

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