RAUtils.m 62 KB

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