RAUtils.m 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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 "ZipArchive.h"
  14. @implementation RAUtils
  15. +(NSString*) getdbzip
  16. {
  17. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  18. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  19. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  20. NSString* temp = NSTemporaryDirectory();
  21. NSString* uuid=[[NSUUID UUID] UUIDString];
  22. NSString *tempfile = [temp stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",uuid]];
  23. ZipArchive* zip = [[ZipArchive alloc] init];
  24. BOOL result = [zip CreateZipFile2:tempfile Password:@"usai2010"];
  25. result = [zip addFileToZip:database_path newname:[database_path lastPathComponent]];
  26. return tempfile;
  27. }
  28. +(NSData*) getdbfile
  29. {
  30. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  31. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  32. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  33. return [NSData dataWithContentsOfFile:database_path];
  34. }
  35. +(NSDictionary*) dictfromfile:(NSString*) path
  36. {
  37. NSData *filedata = [NSData dataWithContentsOfFile:path];
  38. NSError *error = nil;
  39. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
  40. options: NSJSONReadingMutableContainers
  41. error: &error];
  42. // NSLog(@"%@",string2dic);
  43. return string2dic;
  44. }
  45. + (NSArray*) allFilesAtPath:(NSString*) dirString
  46. {
  47. NSMutableArray* array = [NSMutableArray arrayWithCapacity:10];
  48. NSFileManager* fileMgr = [NSFileManager defaultManager];
  49. NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:dirString error:nil];
  50. for (NSString* fileName in tempArray) {
  51. BOOL flag = YES;
  52. NSString* fullPath = [dirString stringByAppendingPathComponent:fileName];
  53. if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
  54. if (!flag) {
  55. [array addObject:fullPath];
  56. }
  57. }
  58. }
  59. return array;
  60. }
  61. + (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {
  62. NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);
  63. NSFileManager *fm = [NSFileManager defaultManager];
  64. NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
  65. NSString *subPath;
  66. while ((subPath = [srcDirEnum nextObject])) {
  67. NSLog(@" subPath: %@", subPath);
  68. NSString *srcFullPath = [srcDir stringByAppendingPathComponent:subPath];
  69. NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];
  70. // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
  71. BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
  72. // Create directory, or delete existing file and move file to destination
  73. if (isDirectory) {
  74. NSLog(@" create directory");
  75. [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
  76. if (err && *err) {
  77. NSLog(@"ERROR: %@", *err);
  78. return false;
  79. }
  80. }
  81. else {
  82. if ([fm fileExistsAtPath:potentialDstPath]) {
  83. NSLog(@" removeItemAtPath");
  84. [fm removeItemAtPath:potentialDstPath error:err];
  85. if (err && *err) {
  86. NSLog(@"ERROR: %@", *err);
  87. return false;
  88. }
  89. }
  90. NSLog(@" moveItemAtPath");
  91. [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
  92. if (err && *err) {
  93. NSLog(@"ERROR: %@", *err);
  94. return false;
  95. }
  96. }
  97. }
  98. [fm removeItemAtPath:srcDir error:err];
  99. if (err && *err) {
  100. NSLog(@"ERROR: %@", *err);
  101. return false;
  102. }
  103. return true;
  104. }
  105. +(void) enum_font
  106. {
  107. return;
  108. NSArray *familys = [UIFont familyNames];
  109. for (int i = 0; i < familys.count; i++)
  110. {
  111. NSString *family = [familys objectAtIndex:i];
  112. NSLog(@"=====Fontfamily:%@", family);
  113. NSArray *fonts = [UIFont fontNamesForFamilyName:family];
  114. for(int j = 0; j < fonts.count; j++)
  115. {
  116. NSLog(@"***FontName:%@", [fonts objectAtIndex:j]);
  117. }
  118. }
  119. }
  120. +(NSTextCheckingResult*) expression_findfistMatch:(NSString*)content regex:(NSString*) pattern
  121. {
  122. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:nil error:nil];
  123. NSTextCheckingResult *match = [regex firstMatchInString:content options:nil range:NSMakeRange(0, content.length)];
  124. return match;
  125. // if (matches) {
  126. // for (NSTextCheckingResult *match in matches) {
  127. // for (int i = 0; i < match.numberOfRanges; ++i) {
  128. // NSLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
  129. // }
  130. // }
  131. // }
  132. // return matches;
  133. }
  134. +(NSArray*) expression_varable:(NSString*)content regex:(NSString*) pattern
  135. {
  136. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:nil error:nil];
  137. NSArray *matches = [regex matchesInString:content options:nil range:NSMakeRange(0, content.length)];
  138. if (matches) {
  139. for (NSTextCheckingResult *match in matches) {
  140. for (int i = 0; i < match.numberOfRanges; ++i) {
  141. NSLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
  142. }
  143. }
  144. }
  145. return matches;
  146. }
  147. + (CGRect)rectAlign:(CGRect )parent rect:(CGRect)rect hAlign:(NSString*)hAlign vAlign:(NSString*)vAlign
  148. {
  149. // double cx=parent.origin.x+parent.size.width/2;
  150. // double cy=parent.origin.y+parent.size.height/2;
  151. CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
  152. if([hAlign.lowercaseString isEqualToString:@"center"])
  153. {
  154. rect=CGRectMake(centerpoint.x-rect.size.width/2, rect.origin.y, rect.size.width, rect.size.height);
  155. }
  156. else
  157. if([hAlign.lowercaseString isEqualToString:@"left"])
  158. {
  159. rect=CGRectMake(parent.origin.x, rect.origin.y, rect.size.width, rect.size.height);
  160. }
  161. if([vAlign.lowercaseString isEqualToString:@"middle"])
  162. {
  163. rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
  164. }
  165. return rect;
  166. }
  167. +(NSString*) get_config_path
  168. {
  169. NSString *default_path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
  170. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  171. NSString *cache_folder=[paths objectAtIndex:0];
  172. NSString* ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
  173. NSString *config_path = [cache_folder stringByAppendingPathComponent:[NSString stringWithFormat: @"config_%@.plist",ver]];
  174. BOOL bdir=NO;
  175. NSFileManager* fileManager = [NSFileManager defaultManager];
  176. if(! [fileManager fileExistsAtPath:config_path isDirectory:&bdir])
  177. {
  178. NSError * error=nil;
  179. if(![fileManager copyItemAtPath:default_path toPath:config_path error:&error])
  180. {
  181. return nil;
  182. }
  183. }
  184. return config_path;
  185. }
  186. + (CGRect)rectVAlign:(CGRect )parent rect:(CGRect)rect vAlign:(NSString*)vAlign
  187. {
  188. // double cx=parent.origin.x+parent.size.width/2;
  189. // double cy=parent.origin.y+parent.size.height/2;
  190. CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
  191. if([vAlign.lowercaseString isEqualToString:@"middle"])
  192. {
  193. rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
  194. }
  195. return rect;
  196. }
  197. + (CGRect)scaleToSize:(CGRect )from to:(CGSize)to
  198. {
  199. if(from.size.width/from.size.height>to.width/to.height)
  200. {
  201. return CGRectMake(from.origin.x, from.origin.y, to.width, to.width*from.size.height/from.size.width);
  202. }
  203. else
  204. {
  205. return CGRectMake(from.origin.x, from.origin.y, to.height*from.size.width/from.size.height, to.height);
  206. }
  207. // // 创建一个bitmap的context
  208. // // 并把它设置成为当前正在使用的context
  209. // UIGraphicsBeginImageContext(size);
  210. // // 绘制改变大小的图片
  211. // [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
  212. // // 从当前context中创建一个改变大小后的图片
  213. // UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  214. // // 使当前的context出堆栈
  215. // UIGraphicsEndImageContext();
  216. // // 返回新的改变大小后的图片
  217. //
  218. // // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
  219. // return scaledImage;
  220. }
  221. + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
  222. // 创建一个bitmap的context
  223. // 并把它设置成为当前正在使用的context
  224. UIGraphicsBeginImageContext(size);
  225. // 绘制改变大小的图片
  226. [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
  227. // 从当前context中创建一个改变大小后的图片
  228. UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  229. // 使当前的context出堆栈
  230. UIGraphicsEndImageContext();
  231. // 返回新的改变大小后的图片
  232. // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
  233. return scaledImage;
  234. }
  235. +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size
  236. {
  237. //UIImage *image=[UIImage imageNamed:@"xxoo.jpeg"];
  238. NSData *imageData=UIImageJPEGRepresentation(image, 1.f);
  239. if(size>imageData.length/1024)
  240. return image;
  241. // CGFloat size=40.f;// kb
  242. CGFloat scale=size/(imageData.length/1024);
  243. scale = sqrt (scale);
  244. CGSize newsize=image.size;
  245. newsize.height = newsize.height*scale;
  246. newsize.width = newsize.width*scale;
  247. return [RAUtils scaleToSize:image size:newsize];
  248. // NSData *newData=UIImageJPEGRepresentation(image, scale);
  249. // UIImage* ret= [[UIImage alloc] initWithData:newData];
  250. //
  251. // return ret;
  252. }
  253. +(NSString*) FloatFormat:(float)value
  254. {
  255. if (fmodf(value, 1)==0)
  256. {
  257. return [NSString stringWithFormat:@"%.0f",value];
  258. } else if (fmodf(value*10, 1)==0)
  259. {
  260. return [NSString stringWithFormat:@"%.1f",value];
  261. }
  262. else if (fmodf(value*100, 1)==0)
  263. {
  264. return [NSString stringWithFormat:@"%.2f",value];
  265. }
  266. else if (fmodf(value*1000, 1)==0)
  267. {
  268. return [NSString stringWithFormat:@"%.3f",value];
  269. }
  270. else
  271. {
  272. return [NSString stringWithFormat:@"%.4f",value];
  273. }
  274. return nil;
  275. }
  276. +(UIViewController*) getViewController:(UIView*) view
  277. {
  278. for (UIView* next = [view superview]; next; next = next.superview) {
  279. UIResponder* nextResponder = [next nextResponder];
  280. if ([nextResponder isKindOfClass:[UIViewController class]]) {
  281. return (UIViewController*)nextResponder;
  282. }
  283. }
  284. return nil;
  285. }
  286. + (float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
  287. {
  288. NSFileManager *fileManager = [[NSFileManager alloc] init];
  289. float size =0;
  290. NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
  291. for(int i = 0; i<[array count]; i++)
  292. {
  293. NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
  294. BOOL isDir;
  295. if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
  296. {
  297. NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
  298. size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
  299. }
  300. else
  301. {
  302. size+=[self fileSizeForDir:fullPath];
  303. }
  304. }
  305. return size;
  306. }
  307. +(NSDictionary*) error_dict:(NSError*)error
  308. {
  309. if(error==nil)
  310. return nil;
  311. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  312. [ret setValue:[NSString stringWithFormat:@"%d",error.code] forKey:@"error_code"];
  313. [ret setValue:error.domain forKey:@"err_domain"];
  314. [ret setValue:[error localizedDescription] forKey:@"err_message"];
  315. // [ret setObject:error.userInfo forKey:@"user_info"];
  316. return ret;
  317. }
  318. +(NSString*) current_date
  319. {
  320. NSDate * date = [NSDate date];
  321. NSTimeInterval sec = [date timeIntervalSinceNow];
  322. NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
  323. NSDateFormatter * df = [[NSDateFormatter alloc] init ];
  324. [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  325. NSString * na = [df stringFromDate:currentDate];
  326. return na;
  327. }
  328. +(void) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
  329. {
  330. if(title==nil)
  331. title = @"Message";
  332. return [self alert_view:msg title:title];
  333. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
  334. //block代码块取代了delegate
  335. // [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  336. // textField.text = self.save_name;
  337. //
  338. //
  339. // }];
  340. // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  341. //
  342. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
  343. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  344. //
  345. // NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
  346. //
  347. // dispatch_async(dispatch_get_main_queue(), ^{
  348. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  349. //
  350. //
  351. // if([[return_json valueForKey:@"result"] intValue]==2)
  352. // {
  353. //
  354. // [RAUtils error_alert:nil title:@"Order Delete"] ;
  355. // }
  356. // else
  357. // {
  358. // [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
  359. // }
  360. //
  361. //
  362. //
  363. //
  364. // });
  365. // });
  366. //
  367. //
  368. // }];
  369. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  370. //NSLog(@"Cancel");
  371. }];
  372. // [alertControl addAction:actionOne];
  373. [alertControl addAction:alertthree];
  374. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  375. }];
  376. [alertControl addAction:alertcancel];
  377. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  378. [vc presentViewController:alertControl animated:YES completion:nil];
  379. return;
  380. }
  381. +(void) neworder:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart
  382. {
  383. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
  384. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  385. NSDictionary* return_json = [iSalesNetwork new_Order];
  386. dispatch_async(dispatch_get_main_queue(), ^{
  387. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  388. if([[return_json valueForKey:@"result"] intValue]==2)
  389. {
  390. int result=[[return_json valueForKey:@"result"] intValue];
  391. if(result==2)
  392. {
  393. //successed.
  394. NSString* order_code = [return_json valueForKey:@"orderCode"];
  395. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  396. appDelegate.order_code = order_code;
  397. appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
  398. [holder performSelector:addtocart];
  399. // [self ReloadData];
  400. // if(self.shopCartBlock!=nil)
  401. // {
  402. // UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
  403. //
  404. //
  405. // CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
  406. // UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
  407. // iv.image = img;
  408. // // [self.contentView addSubview:iv];
  409. // self.shopCartBlock(iv);
  410. //
  411. // }
  412. }
  413. }
  414. else
  415. {
  416. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Create Order" controller:vc] ;
  417. }
  418. });
  419. });
  420. }
  421. +(void) add_to_cart:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart
  422. {
  423. UIApplication * app = [UIApplication sharedApplication];
  424. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  425. MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  426. if(appDelegate.bLogin==false)
  427. {
  428. LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
  429. loginvc.returnValue = ^(bool blogin){
  430. if(blogin)
  431. {
  432. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE*/ true)
  433. {
  434. [main_vc checklogin:false];
  435. NSString* msg =@"";
  436. // if(appDelegate.contact_id.length>0)
  437. // {
  438. // msg = [msg stringByAppendingString:@"Customer:"];
  439. // msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  440. //
  441. // }
  442. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  443. //block代码块取代了delegate
  444. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  445. // vc.disable_refresh = true;
  446. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  447. ovc.showNavibar = true;
  448. //ovc.customer_id = appDelegate.contact_id;
  449. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  450. [holder performSelector:addtocart];
  451. };
  452. ovc.init_style = OL_OPEN;
  453. ovc.onCancel = ^(){
  454. // self.disable_refresh = false;
  455. };
  456. [vc.navigationController pushViewController:ovc animated:true];
  457. }];
  458. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  459. {
  460. //create new;
  461. // self.disable_refresh = true;
  462. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  463. {
  464. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  465. cvc.showNavibar = true;
  466. cvc.contact_type = @"Sales_Order_Customer";
  467. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  468. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  469. appDelegate.customerInfo = value;
  470. if(appDelegate.order_code==nil)
  471. [self neworder:vc selectorholder:holder selector:addtocart];
  472. // neworder();
  473. // [main_vc checklogin:true];
  474. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  475. //
  476. // if(self.returnValue)
  477. // self.returnValue(value);
  478. };
  479. cvc.onCancel = ^(){
  480. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  481. // self.disable_refresh = false;
  482. };
  483. cvc.onReset = ^(){
  484. // [main_vc checklogin:true];
  485. };
  486. [vc.navigationController pushViewController:cvc animated:true];
  487. }
  488. else
  489. {
  490. [self neworder:vc selectorholder:holder selector:addtocart];
  491. }
  492. }
  493. NSLog(@"No");
  494. }];
  495. [alertControl addAction:actionOne];
  496. [alertControl addAction:alertthree];
  497. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  498. }];
  499. [alertControl addAction:alertcancel];
  500. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  501. [vc presentViewController:alertControl animated:YES completion:nil];
  502. }
  503. else
  504. {
  505. //customer login;
  506. [main_vc checklogin:false];
  507. //[self addtocart];
  508. [holder performSelector:addtocart];
  509. }
  510. }
  511. };
  512. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
  513. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  514. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  515. [vc presentViewController:navi animated:YES completion:^{
  516. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  517. NSLog(@"LoginViewController present.........");
  518. // self.btop = false;
  519. // <#code#>
  520. }];
  521. }
  522. else
  523. {
  524. if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
  525. {
  526. if(appDelegate.contact_id.length==0)
  527. {
  528. NSString* msg =@"";
  529. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  530. //block代码块取代了delegate
  531. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  532. // vc.disable_refresh = true;
  533. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  534. ovc.showNavibar = true;
  535. //ovc.customer_id = appDelegate.contact_id;
  536. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  537. [holder performSelector:addtocart];
  538. };
  539. ovc.init_style = OL_OPEN;
  540. ovc.onCancel = ^(){
  541. // self.disable_refresh = false;
  542. };
  543. [vc.navigationController pushViewController:ovc animated:true];
  544. }];
  545. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  546. {
  547. //create new;
  548. // self.disable_refresh = true;
  549. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  550. {
  551. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  552. cvc.showNavibar = true;
  553. cvc.contact_type = @"Sales_Order_Customer";
  554. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  555. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  556. appDelegate.customerInfo = value;
  557. if(appDelegate.order_code==nil)
  558. [self neworder:vc selectorholder:holder selector:addtocart];
  559. // neworder();
  560. // [main_vc checklogin:true];
  561. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  562. //
  563. // if(self.returnValue)
  564. // self.returnValue(value);
  565. };
  566. cvc.onCancel = ^(){
  567. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  568. // self.disable_refresh = false;
  569. };
  570. cvc.onReset = ^(){
  571. // [main_vc checklogin:true];
  572. };
  573. [vc.navigationController pushViewController:cvc animated:true];
  574. }
  575. else
  576. {
  577. [self neworder:vc selectorholder:holder selector:addtocart];
  578. }
  579. }
  580. NSLog(@"No");
  581. }];
  582. [alertControl addAction:actionOne];
  583. [alertControl addAction:alertthree];
  584. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  585. }];
  586. [alertControl addAction:alertcancel];
  587. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  588. [vc presentViewController:alertControl animated:YES completion:nil];
  589. }
  590. else
  591. {
  592. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Checking Pending Order"];
  593. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  594. NSDictionary* return_json = [iSalesNetwork request_PendingOrder:appDelegate.contact_id];
  595. dispatch_async(dispatch_get_main_queue(), ^{
  596. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  597. if([[return_json valueForKey:@"result"] intValue]==2)
  598. {
  599. bool openPendingOrder= [[return_json valueForKey:@"hasPending"] boolValue];
  600. bool createNewOrder=appDelegate.can_create_order;
  601. if(openPendingOrder&&createNewOrder)
  602. {
  603. NSString* msg =@"";
  604. if(appDelegate.contact_id.length>0)
  605. {
  606. msg = [msg stringByAppendingString:@"Customer:"];
  607. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  608. }
  609. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  610. //block代码块取代了delegate
  611. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  612. // vc.disable_refresh = true;
  613. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  614. ovc.showNavibar = true;
  615. ovc.customer_id = appDelegate.contact_id;
  616. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  617. [holder performSelector:addtocart];
  618. };
  619. ovc.init_style = OL_OPEN;
  620. ovc.onCancel = ^(){
  621. // self.disable_refresh = false;
  622. };
  623. [vc.navigationController pushViewController:ovc animated:true];
  624. }];
  625. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  626. {
  627. //create new;
  628. // self.disable_refresh = true;
  629. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  630. {
  631. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  632. cvc.showNavibar = true;
  633. cvc.contact_type = @"Sales_Order_Customer";
  634. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  635. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  636. appDelegate.customerInfo = value;
  637. if(appDelegate.order_code==nil)
  638. [self neworder:vc selectorholder:holder selector:addtocart];
  639. // neworder();
  640. // [main_vc checklogin:true];
  641. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  642. //
  643. // if(self.returnValue)
  644. // self.returnValue(value);
  645. };
  646. cvc.onCancel = ^(){
  647. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  648. // self.disable_refresh = false;
  649. };
  650. cvc.onReset = ^(){
  651. // [main_vc checklogin:true];
  652. };
  653. [vc.navigationController pushViewController:cvc animated:true];
  654. }
  655. else
  656. {
  657. [self neworder:vc selectorholder:holder selector:addtocart];
  658. }
  659. }
  660. NSLog(@"No");
  661. }];
  662. [alertControl addAction:actionOne];
  663. [alertControl addAction:alertthree];
  664. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  665. }];
  666. [alertControl addAction:alertcancel];
  667. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  668. [vc presentViewController:alertControl animated:YES completion:nil];
  669. }
  670. else
  671. {
  672. if(openPendingOrder)
  673. {
  674. NSString* msg =@"";
  675. if(appDelegate.contact_id.length>0)
  676. {
  677. msg = [msg stringByAppendingString:@"Customer:"];
  678. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  679. }
  680. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  681. //block代码块取代了delegate
  682. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Check for saved order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  683. // vc.disable_refresh = true;
  684. OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  685. ovc.showNavibar = true;
  686. ovc.customer_id = appDelegate.contact_id;
  687. ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  688. [holder performSelector:addtocart];
  689. };
  690. ovc.init_style = OL_OPEN;
  691. ovc.onCancel = ^(){
  692. // self.disable_refresh = false;
  693. };
  694. [vc.navigationController pushViewController:ovc animated:true];
  695. }];
  696. [alertControl addAction:actionOne];
  697. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  698. }];
  699. [alertControl addAction:alertcancel];
  700. // [alertControl addAction:alertthree];
  701. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  702. [vc presentViewController:alertControl animated:YES completion:nil];
  703. }
  704. else if(createNewOrder)
  705. {
  706. NSString* msg =@"";
  707. if(appDelegate.contact_id.length>0)
  708. {
  709. msg = [msg stringByAppendingString:@"Customer:"];
  710. msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  711. }
  712. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
  713. //block代码块取代了delegate
  714. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  715. {
  716. //create new;
  717. // self.disable_refresh = true;
  718. if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  719. {
  720. ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  721. cvc.showNavibar = true;
  722. cvc.contact_type = @"Sales_Order_Customer";
  723. cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  724. appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  725. appDelegate.customerInfo = value;
  726. if(appDelegate.order_code==nil)
  727. [self neworder:vc selectorholder:holder selector:addtocart];
  728. // neworder();
  729. // [main_vc checklogin:true];
  730. // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  731. //
  732. // if(self.returnValue)
  733. // self.returnValue(value);
  734. };
  735. cvc.onCancel = ^(){
  736. [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order Error" controller:vc];
  737. // self.disable_refresh = false;
  738. };
  739. cvc.onReset = ^(){
  740. // [main_vc checklogin:true];
  741. };
  742. [vc.navigationController pushViewController:cvc animated:true];
  743. }
  744. else
  745. {
  746. [self neworder:vc selectorholder:holder selector:addtocart];
  747. }
  748. }
  749. NSLog(@"No");
  750. }];
  751. // [alertControl addAction:actionOne];
  752. [alertControl addAction:alertthree];
  753. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  754. }];
  755. [alertControl addAction:alertcancel];
  756. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  757. [vc presentViewController:alertControl animated:YES completion:nil];
  758. }
  759. else
  760. {
  761. [RAUtils message_alert:[return_json valueForKey:@"You donot have permission to access order"] title:@"Add To Cart" controller:vc];
  762. }
  763. }
  764. }
  765. else
  766. {
  767. [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Check Pending Order" controller:vc] ;
  768. }
  769. });
  770. });
  771. }
  772. // // [main_vc checklogin:false];
  773. //
  774. // if(appDelegate.can_create_order)
  775. // {
  776. // NSString* msg =@"";
  777. // if(appDelegate.contact_id.length>0)
  778. // {
  779. // msg = [msg stringByAppendingString:@"\n\nCustomer:"];
  780. // msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  781. //
  782. // }
  783. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
  784. //
  785. // // alert.
  786. // [alert show];
  787. // }
  788. // else
  789. // {
  790. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil), nil];
  791. //
  792. // // alert.
  793. // [alert show];
  794. // }
  795. }
  796. else
  797. {
  798. // if(appDelegate.order_code==nil)
  799. // [ self neworder];
  800. // else
  801. [holder performSelector:addtocart];
  802. }
  803. }
  804. }
  805. +(void) add_recent_model:(NSDictionary*) model
  806. {
  807. NSMutableDictionary * newdict = [[NSMutableDictionary alloc]init];
  808. [newdict setObject:model forKey:@"item_0"];
  809. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  810. int count=[appDelegate.recent_model[@"count"] intValue];
  811. for(int i=0;i<count;i++)
  812. {
  813. NSMutableDictionary * mitem= appDelegate.recent_model[[NSString stringWithFormat:@"item_%d",i]];
  814. if([mitem[@"product_id"] isEqualToString:model[@"product_id"]])
  815. continue;
  816. [newdict setObject:mitem forKey:[NSString stringWithFormat:@"item_%lu",(unsigned long)newdict.allKeys.count]];
  817. }
  818. newdict[@"count"]=[NSString stringWithFormat:@"%lu",(unsigned long)newdict.allKeys.count];
  819. appDelegate.recent_model = newdict;
  820. //
  821. //
  822. // if(!bexist)
  823. // {
  824. // [appDelegate.recent_model setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
  825. // appDelegate.recent_model[@"count"]=[NSString stringWithFormat:@"%d",count+1];
  826. // }
  827. }
  828. +(void) alert_view :(NSString*) msg title:(NSString*) title
  829. {
  830. if(title==nil)
  831. title = @"Message";
  832. if(msg.length>0)
  833. {
  834. title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
  835. }
  836. UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
  837. [alert show];
  838. }
  839. + (long long) freeDiskSpaceInMegaBytes{
  840. struct statfs buf;
  841. long long freespace = -1;
  842. if(statfs("/var", &buf) >= 0){
  843. freespace = (long long)(buf.f_bsize * buf.f_bfree);
  844. }
  845. NSLog([NSString stringWithFormat:@"手机剩余存储空间为:%qi MB" ,freespace/1024/1024]);
  846. return freespace/1024/1024;
  847. }
  848. +(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
  849. {
  850. if(title==nil)
  851. title = @"Please Wait";
  852. if(msg==nil)
  853. msg= @"Waiting...";
  854. NSAssert(msg!=nil, @"error message from json is nil");
  855. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  856. [alert show];
  857. //
  858. //
  859. // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
  860. // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  861. // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
  862. //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
  863. //// [alert setValue:aiView forKey:@"accessoryView"];
  864. //// }else{
  865. //// [alert addSubview:aiView];
  866. //// }
  867. //
  868. // aiView.hidden = false;
  869. // aiView.hidesWhenStopped = false;
  870. // [aiView startAnimating];
  871. //
  872. //[alert addSubview:aiView];
  873. return alert;
  874. //return nil;
  875. // return alert;
  876. // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
  877. //[alert show];
  878. }
  879. +(NSDictionary*) device_info
  880. {
  881. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  882. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  883. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  884. NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
  885. NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
  886. [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  887. [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
  888. [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
  889. [info setValue:versionNum forKey:@"ver"];
  890. [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
  891. return info;
  892. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  893. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  894. // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
  895. }
  896. +(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
  897. {
  898. NSArray *stringArray = [string componentsSeparatedByString:separator];
  899. return stringArray;
  900. }
  901. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim
  902. {
  903. if(arr.count==0)
  904. return nil;
  905. NSMutableArray * marr = [arr mutableCopy];
  906. begin:
  907. for (NSString* item in marr) {
  908. if(item.length==0 )
  909. if( btrim)
  910. {
  911. [marr removeObject:item];
  912. goto begin;
  913. }
  914. }
  915. NSString * ret = [marr componentsJoinedByString:separator];
  916. return ret;
  917. }
  918. +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets
  919. {
  920. if(brackets!=nil)
  921. separator = [NSString stringWithFormat:@"%@%@%@",brackets,separator,brackets];
  922. NSMutableArray * marr = [arr mutableCopy];
  923. begin:
  924. for (NSString* item in marr) {
  925. if(item.length==0 )
  926. if( btrim)
  927. {
  928. [marr removeObject:item];
  929. goto begin;
  930. }
  931. }
  932. NSString * ret = [marr componentsJoinedByString:separator];
  933. if(brackets!=nil)
  934. ret = [NSString stringWithFormat:@"%@%@%@",brackets,ret,brackets];
  935. return ret;
  936. }
  937. +(NSDictionary*) string2dict:(NSString*) str
  938. {
  939. if(str==nil)
  940. return nil;
  941. NSError *error = nil;
  942. NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
  943. options: NSJSONReadingMutableContainers
  944. error: &error];
  945. NSLog(@"%@",string2dic);
  946. return string2dic;
  947. }
  948. +(UIColor*) strColor:(NSString*) color
  949. {
  950. if([color.lowercaseString isEqualToString:@"red"])
  951. return [UIColor redColor];
  952. return [UIColor blackColor];
  953. }
  954. +(NSData*) dict2data:(NSDictionary*) dict
  955. {
  956. if(dict==nil)
  957. return nil;
  958. // 将NSDictionary转化为NSData
  959. NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
  960. return data;
  961. }
  962. +(NSString*) dict2string:(NSDictionary*) dict
  963. {
  964. if(dict==nil)
  965. return nil;
  966. // 将NSDictionary转化为NSData
  967. NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
  968. // 再将NSData转为字符串
  969. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  970. return jsonStr;
  971. }
  972. +(NSString*) base64en:(NSString*) string
  973. {
  974. if(string == nil)
  975. return nil;
  976. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  977. NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
  978. return stringBase64;
  979. }
  980. +(NSString*) base64de:(NSString*) stringBase64
  981. {
  982. if(stringBase64==nil)
  983. return nil;
  984. NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
  985. NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  986. return string;
  987. }
  988. +(void) deletefiles :(NSString*) path
  989. {
  990. // NSString *extension = @"m4r";
  991. NSFileManager *fileManager = [NSFileManager defaultManager];
  992. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  993. // NSString *documentsDirectory = [paths objectAtIndex:0];
  994. NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
  995. NSEnumerator *e = [contents objectEnumerator];
  996. NSString *filename;
  997. while ((filename = [e nextObject])) {
  998. bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
  999. if(!result)
  1000. NSLog(@"delete file failed %@------%@",path,filename);
  1001. }
  1002. }
  1003. +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
  1004. {
  1005. if(json==nil)
  1006. return nil;
  1007. NSMutableArray* ret = [[NSMutableArray alloc] init];
  1008. int count = [[json valueForKey:count_fields] intValue];
  1009. NSDictionary* items = nil;
  1010. if(items_mark==nil)
  1011. items = json;
  1012. else
  1013. items = [json objectForKey:items_mark];
  1014. for(int i=0;i<count;i++)
  1015. {
  1016. NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
  1017. [ret addObject:obj];
  1018. }
  1019. return ret;
  1020. }
  1021. +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
  1022. {
  1023. NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
  1024. //#define RESULT_FALSE 0
  1025. //#define RESULT_TRUE 2
  1026. //#define RESULT_NET_ERROR -3
  1027. //#define RESULT_NET_NOTAVAILABLE -4
  1028. //#define RESULT_ERROR -5
  1029. //#define RESULT_LOCALFILE_ERROR -7
  1030. //#define RESULT_USERAUTH_ERROR -9
  1031. //#define RESULT_UPDATE_USERAUTH_ERROR -11
  1032. //#define RESULT_SESSION_EXPIRED -13
  1033. //#define RESULT_VER_LOW
  1034. if(msg.length<=0)
  1035. {
  1036. switch (code) {
  1037. case RESULT_NET_NOTAVAILABLE:
  1038. msg= MSG_NET_NOTAVAILABLE;
  1039. break;
  1040. default:
  1041. // assert(@"UNDEFINE ERROR CODE!");
  1042. break;
  1043. }
  1044. }
  1045. // if(code==RESULT_NET_NOTAVAILABLE)
  1046. // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
  1047. // else
  1048. [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
  1049. [ret setValue:msg forKey:@"err_msg"];
  1050. // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
  1051. // options:0
  1052. // error:nil];
  1053. return ret;
  1054. }
  1055. + (CGRect)relativeFrameForScreenWithView:(UIView *)v
  1056. {
  1057. UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
  1058. CGRect rect=[v convertRect: v.bounds toView:window];
  1059. return rect;
  1060. // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
  1061. //
  1062. // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  1063. // if (!iOS7) {
  1064. // screenHeight -= 20;
  1065. // }
  1066. // UIView *view = v;
  1067. // CGFloat x = .0;
  1068. // CGFloat y = .0;
  1069. // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
  1070. // x += view.frame.origin.x;
  1071. // y += view.frame.origin.y;
  1072. // view = view.superview;
  1073. // if ([view isKindOfClass:[UIScrollView class]]) {
  1074. // x -= ((UIScrollView *) view).contentOffset.x;
  1075. // y -= ((UIScrollView *) view).contentOffset.y;
  1076. // }
  1077. // }
  1078. // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
  1079. }
  1080. @end