RAUtils.m 36 KB

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