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. +(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. +(NSString*) current_date_forfile
  342. {
  343. NSDate * date = [NSDate date];
  344. NSTimeInterval sec = [date timeIntervalSinceNow];
  345. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  346. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  347. [df setDateFormat:@"MM_dd_yyyy_HH_mm_ss"];
  348. NSString * na = [df stringFromDate:currentDate];
  349. return na;
  350. }
  351. +(void) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  352. {
  353. if(title==nil)
  354. title = @"Message";
  355. if ([title isEqualToString:@"Add To Cart"]) {
  356. if ([msg hasPrefix:@"Out of Stock.\n"]) {
  357. title = @"Add To Cart: Out of Stock";
  358. msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
  359. }
  360. }
  361. return [self alert_view:msg title:title];
  362. //
  363. //
  364. // UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
  365. // //block代码块取代了delegate
  366. //
  367. //
  368. // // [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  369. // // textField.text = self.save_name;
  370. // //
  371. // //
  372. // // }];
  373. //
  374. // // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  375. // //
  376. // // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
  377. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  378. // //
  379. // // NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
  380. // //
  381. // // dispatch_async(dispatch_get_main_queue(), ^{
  382. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  383. // //
  384. // //
  385. // // if([[return_json valueForKey:@"result"] intValue]==2)
  386. // // {
  387. // //
  388. // // [RAUtils error_alert:nil title:@"Order Delete"] ;
  389. // // }
  390. // // else
  391. // // {
  392. // // [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
  393. // // }
  394. // //
  395. // //
  396. // //
  397. // //
  398. // // });
  399. // // });
  400. // //
  401. // //
  402. // // }];
  403. //
  404. // UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  405. // //DebugLog(@"Cancel");
  406. // }];
  407. // // [alertControl addAction:actionOne];
  408. //
  409. // [alertControl addAction:alertthree];
  410. //
  411. //
  412. // UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  413. // }];
  414. // [alertControl addAction:alertcancel];
  415. // //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  416. //
  417. //
  418. //
  419. //
  420. // [vc presentViewController:alertControl animated:YES completion:nil];
  421. //
  422. //
  423. //
  424. // return;
  425. //
  426. //
  427. }
  428. +(void) alert_view :(NSString*) msg title:(NSString*) title
  429. {
  430. if(title==nil)
  431. title = @"Message";
  432. if(msg.length>0)
  433. {
  434. title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
  435. }
  436. UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
  437. [alert show];
  438. }
  439. + (long long) freeDiskSpaceInMegaBytes{
  440. struct statfs buf;
  441. long long freespace = -1;
  442. if(statfs("/var", &buf) >= 0){
  443. freespace = (long long)(buf.f_bsize * buf.f_bfree);
  444. }
  445. DebugLog(@"手机剩余存储空间为:%qi MB" ,freespace/1024/1024);
  446. return freespace/1024/1024;
  447. }
  448. +(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
  449. {
  450. if(title==nil)
  451. title = @"Please Wait";
  452. if(msg==nil)
  453. msg= @"Waiting...";
  454. NSAssert(msg!=nil, @"error message from json is nil");
  455. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  456. [alert show];
  457. //
  458. //
  459. // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
  460. // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  461. // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
  462. //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
  463. //// [alert setValue:aiView forKey:@"accessoryView"];
  464. //// }else{
  465. //// [alert addSubview:aiView];
  466. //// }
  467. //
  468. // aiView.hidden = false;
  469. // aiView.hidesWhenStopped = false;
  470. // [aiView startAnimating];
  471. //
  472. //[alert addSubview:aiView];
  473. return alert;
  474. //return nil;
  475. // return alert;
  476. // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
  477. //[alert show];
  478. }
  479. +(NSDictionary*) device_info
  480. {
  481. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  482. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  483. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  484. NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
  485. NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
  486. [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  487. [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
  488. [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
  489. [info setValue:versionNum forKey:@"ver"];
  490. [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
  491. return info;
  492. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  493. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  494. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  495. }
  496. +(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
  497. {
  498. NSArray *stringArray = [string componentsSeparatedByString:separator];
  499. return stringArray;
  500. }
  501. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim
  502. {
  503. if(arr.count==0)
  504. return nil;
  505. NSMutableArray * marr = [arr mutableCopy];
  506. begin:
  507. for (NSString* item in marr) {
  508. if(item.length==0 )
  509. if( btrim)
  510. {
  511. [marr removeObject:item];
  512. goto begin;
  513. }
  514. }
  515. NSString * ret = [marr componentsJoinedByString:separator];
  516. return ret;
  517. }
  518. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets
  519. {
  520. if(brackets!=nil)
  521. separator = [NSString stringWithFormat:@"%@%@%@",brackets,separator,brackets];
  522. NSMutableArray * marr = [arr mutableCopy];
  523. begin:
  524. for (NSString* item in marr) {
  525. if(item.length==0 )
  526. if( btrim)
  527. {
  528. [marr removeObject:item];
  529. goto begin;
  530. }
  531. }
  532. NSString * ret = [marr componentsJoinedByString:separator];
  533. if(brackets!=nil)
  534. ret = [NSString stringWithFormat:@"%@%@%@",brackets,ret,brackets];
  535. return ret;
  536. }
  537. +(NSDictionary*) string2dict:(NSString*) str
  538. {
  539. if(str==nil)
  540. return nil;
  541. NSError *error = nil;
  542. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
  543. options: NSJSONReadingMutableContainers
  544. error: &error];
  545. DebugLog(@"%@",string2dic);
  546. return string2dic;
  547. }
  548. +(UIColor*) strColor:(NSString*) color
  549. {
  550. if([color.lowercaseString isEqualToString:@"red"])
  551. return [UIColor redColor];
  552. return [UIColor blackColor];
  553. }
  554. +(NSData*) dict2data:(NSDictionary*) dict
  555. {
  556. if(dict==nil)
  557. return nil;
  558. // 将NSDictionary转化为NSData
  559. NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
  560. return data;
  561. }
  562. +(NSString*) dict2string:(NSDictionary*) dict
  563. {
  564. if(dict==nil)
  565. return nil;
  566. // 将NSDictionary转化为NSData
  567. NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
  568. // 再将NSData转为字符串
  569. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  570. return jsonStr;
  571. }
  572. +(NSString*) base64en:(NSString*) string
  573. {
  574. if(string == nil)
  575. return nil;
  576. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  577. NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
  578. return stringBase64;
  579. }
  580. +(NSString*) base64de:(NSString*) stringBase64
  581. {
  582. if(stringBase64==nil)
  583. return nil;
  584. NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
  585. NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  586. return string;
  587. }
  588. +(void) deletefiles :(NSString*) path
  589. {
  590. // NSString *extension = @"m4r";
  591. NSFileManager *fileManager = [NSFileManager defaultManager];
  592. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  593. // NSString *documentsDirectory = [paths objectAtIndex:0];
  594. NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
  595. NSEnumerator *e = [contents objectEnumerator];
  596. NSString *filename;
  597. while ((filename = [e nextObject])) {
  598. bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
  599. if(!result)
  600. DebugLog(@"delete file failed %@------%@",path,filename);
  601. }
  602. }
  603. +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
  604. {
  605. if(json==nil)
  606. return nil;
  607. NSMutableArray* ret = [[NSMutableArray alloc] init];
  608. int count = [[json valueForKey:count_fields] intValue];
  609. NSDictionary* items = nil;
  610. if(items_mark==nil)
  611. items = json;
  612. else
  613. items = [json objectForKey:items_mark];
  614. for(int i=0;i<count;i++)
  615. {
  616. NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
  617. [ret addObject:obj];
  618. }
  619. return ret;
  620. }
  621. +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
  622. {
  623. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  624. //#define RESULT_FALSE 0
  625. //#define RESULT_TRUE 2
  626. //#define RESULT_NET_ERROR -3
  627. //#define RESULT_NET_NOTAVAILABLE -4
  628. //#define RESULT_ERROR -5
  629. //#define RESULT_LOCALFILE_ERROR -7
  630. //#define RESULT_USERAUTH_ERROR -9
  631. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  632. //#define RESULT_SESSION_EXPIRED -13
  633. //#define RESULT_VER_LOW
  634. if(msg.length<=0)
  635. {
  636. switch (code) {
  637. case RESULT_NET_NOTAVAILABLE:
  638. msg= MSG_NET_NOTAVAILABLE;
  639. break;
  640. default:
  641. // assert(@"UNDEFINE ERROR CODE!");
  642. break;
  643. }
  644. }
  645. // if(code==RESULT_NET_NOTAVAILABLE)
  646. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  647. // else
  648. [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
  649. [ret setValue:msg forKey:@"err_msg"];
  650. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  651. // options:0
  652. // error:nil];
  653. return ret;
  654. }
  655. + (BOOL)isNumeric:(NSString*)string{
  656. NSScanner* scan = [NSScanner scannerWithString:string];
  657. int val;
  658. return[scan scanInt:&val] && [scan isAtEnd];
  659. }
  660. + (CGRect)relativeFrameForScreenWithView:(UIView *)v
  661. {
  662. UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
  663. CGRect rect=[v convertRect: v.bounds toView:window];
  664. return rect;
  665. // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
  666. //
  667. // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  668. // if (!iOS7) {
  669. // screenHeight -= 20;
  670. // }
  671. // UIView *view = v;
  672. // CGFloat x = .0;
  673. // CGFloat y = .0;
  674. // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
  675. // x += view.frame.origin.x;
  676. // y += view.frame.origin.y;
  677. // view = view.superview;
  678. // if ([view isKindOfClass:[UIScrollView class]]) {
  679. // x -= ((UIScrollView *) view).contentOffset.x;
  680. // y -= ((UIScrollView *) view).contentOffset.y;
  681. // }
  682. // }
  683. // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
  684. }
  685. + (BOOL)saveData:(NSData *)data toPath:(NSString *)path {
  686. // NSString *directory = [path stringByDeletingLastPathComponent];
  687. NSFileManager *manager = [NSFileManager defaultManager];
  688. NSString *dir = [path stringByDeletingLastPathComponent];
  689. BOOL create = [manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  690. if (create) {
  691. BOOL save = [manager createFileAtPath:path contents:data attributes:nil];
  692. if (save) {
  693. return YES;
  694. }
  695. return NO;
  696. }
  697. return NO;
  698. }
  699. + (void)removeFileAtPath:(NSString *)path {
  700. if (!path.length) {
  701. return;
  702. }
  703. NSFileManager *manager = [NSFileManager defaultManager];
  704. [manager removeItemAtPath:path error:nil];
  705. }
  706. + (NSString *)appCacheDirectory {
  707. return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  708. }
  709. +(NSString*)md5WithFile:(NSString*)path
  710. {
  711. return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
  712. }
  713. CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
  714. // Declare needed variables
  715. CFStringRef result = NULL;
  716. CFReadStreamRef readStream = NULL;
  717. // Get the file URL
  718. CFURLRef fileURL =
  719. CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
  720. (CFStringRef)filePath,
  721. kCFURLPOSIXPathStyle,
  722. (Boolean)false);
  723. if (!fileURL) goto done;
  724. // Create and open the read stream
  725. readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
  726. (CFURLRef)fileURL);
  727. if (!readStream) goto done;
  728. bool didSucceed = (bool)CFReadStreamOpen(readStream);
  729. if (!didSucceed) goto done;
  730. // Initialize the hash object
  731. CC_MD5_CTX hashObject;
  732. CC_MD5_Init(&hashObject);
  733. // Make sure chunkSizeForReadingData is valid
  734. if (!chunkSizeForReadingData) {
  735. chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
  736. }
  737. // Feed the data to the hash object
  738. bool hasMoreData = true;
  739. while (hasMoreData) {
  740. uint8_t buffer[chunkSizeForReadingData];
  741. CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
  742. if (readBytesCount == -1) break;
  743. if (readBytesCount == 0) {
  744. hasMoreData = false;
  745. continue;
  746. }
  747. CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
  748. }
  749. // Check if the read operation succeeded
  750. didSucceed = !hasMoreData;
  751. // Compute the hash digest
  752. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  753. CC_MD5_Final(digest, &hashObject);
  754. // Abort if the read operation failed
  755. if (!didSucceed) goto done;
  756. // Compute the string result
  757. char hash[2 * sizeof(digest) + 1];
  758. for (size_t i = 0; i < sizeof(digest); ++i) {
  759. snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
  760. }
  761. result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
  762. done:
  763. if (readStream) {
  764. CFReadStreamClose(readStream);
  765. CFRelease(readStream);
  766. }
  767. if (fileURL) {
  768. CFRelease(fileURL);
  769. }
  770. return result;
  771. }
  772. + (BOOL)fileExistsAtPath:(NSString *)path {
  773. NSFileManager *fm = [NSFileManager defaultManager];
  774. return [fm fileExistsAtPath:path];
  775. return NO;
  776. }
  777. + (NSString *)htmlForVideo:(NSString*) iframeCode template:(NSString*) path
  778. {
  779. if(path==nil)
  780. path=[[NSBundle mainBundle] pathForResource:@"photostack_video" ofType:@"html"];
  781. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  782. if(tempate==nil)
  783. return @"";
  784. // NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  785. // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  786. // imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  787. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:iframeCode];
  788. return tempate;
  789. }
  790. + (NSString *)htmlForImage:(UIImage *)image template:(NSString*) path
  791. {
  792. if(path==nil)
  793. path=[[NSBundle mainBundle] pathForResource:@"photostack_image" ofType:@"html"];
  794. NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  795. if(tempate==nil)
  796. return @"";
  797. NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  798. NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
  799. imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
  800. tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:imageSource];
  801. return tempate;
  802. }
  803. @end