| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184 |
- //
- // RAUtils.m
- // RedAnt ERP Mobile
- //
- // Created by Ray on 9/17/15.
- // Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
- //
- #import "RAUtils.h"
- #import "RAConvertor.h"
- #import "const.h"
- //#import "LoginViewController.h"
- //#import "MainViewController.h"
- #import <sys/param.h>
- #import <sys/mount.h>
- //#import "const.h"
- #import "AppDelegate.h"
- //#import "Singleton.h"
- #include <CommonCrypto/CommonDigest.h>
- #import <AudioToolbox/AudioToolbox.h>
- //#import "ZipArchive.h"
- #define FileHashDefaultChunkSizeForReadingData 1024*8
- @implementation RAUtils
- +(int)getRandomNumber:(int)from to:(int)to
- {
- return (int)(from + (arc4random() % (to-from + 1)));
- }
- //+(float)randomf
- //{
- //
- // int irandom = [self getRandomNumber:0 to:5];
- // return irandom / 100.0;
- //}
- +(NSData*) getdbfile:(NSString*)dbname
- {
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
- NSString *database_path = [documents stringByAppendingPathComponent:dbname];
- return [NSData dataWithContentsOfFile:database_path];
-
-
- }
- +(NSDictionary*) dictfromfile:(NSString*) path
- {
- NSData *filedata = [NSData dataWithContentsOfFile:path];
- if(filedata == nil)
- return nil;
- NSError *error = nil;
- NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
- options: NSJSONReadingMutableContainers
- error: &error];
- // DebugLog(@"%@",string2dic);
- return string2dic;
-
- }
- +(void) dicttofile:(NSString*) path dict:(NSDictionary*)dict
- {
-
- NSDictionary* saveddict = dict;
- if(saveddict==nil)
- return;
-
- NSString *filestr =[RAConvertor dict2string:dict];
- NSError *error=nil;
-
- [filestr writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:&error];
- // DebugLog(@"%@",string2dic);
- // return string2dic;
-
- }
- +(NSDictionary* )copyDict:(NSDictionary* ) source
- {
- if(source==nil)
- return nil;
- return [RAConvertor data2dict:[RAConvertor dict2data:source]];
- }
- + (NSArray*) allFilesAtPath:(NSString*) dirString
- {
-
- NSMutableArray* array = [NSMutableArray arrayWithCapacity:10];
-
- NSFileManager* fileMgr = [NSFileManager defaultManager];
-
- NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:dirString error:nil];
-
- for (NSString* fileName in tempArray) {
-
- BOOL flag = YES;
-
- NSString* fullPath = [dirString stringByAppendingPathComponent:fileName];
-
- if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
-
- if (!flag) {
-
- [array addObject:fullPath];
-
- }
-
- }
-
- }
-
- return array;
-
- }
- + (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {
-
- DebugLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);
-
- NSFileManager *fm = [NSFileManager defaultManager];
- NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
- NSString *subPath;
- while ((subPath = [srcDirEnum nextObject])) {
-
- DebugLog(@" subPath: %@", subPath);
- NSString *srcFullPath = [srcDir stringByAppendingPathComponent:subPath];
- NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];
-
- // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
- BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
-
- // Create directory, or delete existing file and move file to destination
- if (isDirectory) {
- DebugLog(@" create directory");
- [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
- if (err && *err) {
- DebugLog(@"ERROR: %@", *err);
- return false;
- }
- }
- else {
- if ([fm fileExistsAtPath:potentialDstPath]) {
- DebugLog(@" removeItemAtPath");
- [fm removeItemAtPath:potentialDstPath error:err];
- if (err && *err) {
- DebugLog(@"ERROR: %@", *err);
- return false;
- }
- }
-
- DebugLog(@" moveItemAtPath");
- [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
- if (err && *err) {
- DebugLog(@"ERROR: %@", *err);
- return false;
- }
- }
- }
- [fm removeItemAtPath:srcDir error:err];
- if (err && *err) {
- DebugLog(@"ERROR: %@", *err);
- return false;
- }
- return true;
- }
- //+(void) enum_font
- //{
- // return;
- // NSArray *familys = [UIFont familyNames];
- //
- // for (int i = 0; i < familys.count; i++)
- // {
- // NSString *family = [familys objectAtIndex:i];
- // DebugLog(@"=====Fontfamily:%@", family);
- // NSArray *fonts = [UIFont fontNamesForFamilyName:family];
- // for(int j = 0; j < fonts.count; j++)
- // {
- // DebugLog(@"***FontName:%@", [fonts objectAtIndex:j]);
- // }
- // }
- //}
- //+(NSTextCheckingResult*) expression_findfistMatch:(NSString*)content regex:(NSString*) pattern
- //{
- // NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
- //
- // NSTextCheckingResult *match = [regex firstMatchInString:content options:0 range:NSMakeRange(0, content.length)];
- // return match;
- //// if (matches) {
- //// for (NSTextCheckingResult *match in matches) {
- //// for (int i = 0; i < match.numberOfRanges; ++i) {
- //// DebugLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
- //// }
- //// }
- //// }
- //// return matches;
- //}
- //+(NSArray*) expression_varable:(NSString*)content regex:(NSString*) pattern
- //{
- //
- // if(content==nil)
- // return nil;
- //
- //
- // NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
- //
- // NSArray *matches = [regex matchesInString:content options:0 range:NSMakeRange(0, content.length)];
- //
- // if (matches) {
- // for (NSTextCheckingResult *match in matches) {
- // for (int i = 0; i < match.numberOfRanges; ++i) {
- // DebugLog(@"-> %@", [content substringWithRange:[match rangeAtIndex:i]]);
- // }
- // }
- // }
- // return matches;
- //}
- + (CGRect)rectAlign:(CGRect )parent rect:(CGRect)rect hAlign:(NSString*)hAlign vAlign:(NSString*)vAlign
- {
- // double cx=parent.origin.x+parent.size.width/2;
- // double cy=parent.origin.y+parent.size.height/2;
- CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
- if([hAlign.lowercaseString isEqualToString:@"center"])
- {
- rect=CGRectMake(centerpoint.x-rect.size.width/2, rect.origin.y, rect.size.width, rect.size.height);
- }
- else
- if([hAlign.lowercaseString isEqualToString:@"left"])
- {
- rect=CGRectMake(parent.origin.x, rect.origin.y, rect.size.width, rect.size.height);
- }
- else
- if([hAlign.lowercaseString isEqualToString:@"right"])
- {
- rect=CGRectMake(parent.origin.x+parent.size.width-rect.size.width, rect.origin.y, rect.size.width, rect.size.height);
- }
- if([vAlign.lowercaseString isEqualToString:@"middle"])
- {
- rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
- }
-
- return rect;
-
- }
- +(NSString*) get_config_path
- {
- NSString *default_path = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *cache_folder=[paths objectAtIndex:0];
-
- NSString* ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
-
- NSString *config_path = [cache_folder stringByAppendingPathComponent:[NSString stringWithFormat: @"config_%@.plist",ver]];
- BOOL bdir=NO;
- NSFileManager* fileManager = [NSFileManager defaultManager];
- if(! [fileManager fileExistsAtPath:config_path isDirectory:&bdir])
- {
- NSError * error=nil;
-
- if(![fileManager copyItemAtPath:default_path toPath:config_path error:&error])
- {
- return nil;
- }
- }
-
-
-
- return config_path;
- }
- + (CGRect)rectVAlign:(CGRect )parent rect:(CGRect)rect vAlign:(NSString*)vAlign
- {
- // double cx=parent.origin.x+parent.size.width/2;
- // double cy=parent.origin.y+parent.size.height/2;
- CGPoint centerpoint= CGPointMake(parent.origin.x+parent.size.width/2,parent.origin.y+parent.size.height/2);
-
- if([vAlign.lowercaseString isEqualToString:@"middle"])
- {
- rect=CGRectMake(rect.origin.x, centerpoint.y-rect.size.height/2, rect.size.width, rect.size.height);
- }
-
- return rect;
-
- }
- + (CGRect)scaleToSize:(CGRect )from to:(CGSize)to
- {
- if(from.size.width/from.size.height>to.width/to.height)
- {
- return CGRectMake(from.origin.x, from.origin.y, to.width, to.width*from.size.height/from.size.width);
- }
- else
- {
- return CGRectMake(from.origin.x, from.origin.y, to.height*from.size.width/from.size.height, to.height);
- }
- // // 创建一个bitmap的context
- // // 并把它设置成为当前正在使用的context
- // UIGraphicsBeginImageContext(size);
- // // 绘制改变大小的图片
- // [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
- // // 从当前context中创建一个改变大小后的图片
- // UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
- // // 使当前的context出堆栈
- // UIGraphicsEndImageContext();
- // // 返回新的改变大小后的图片
- //
- // // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
- // return scaledImage;
- }
- + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
- // 创建一个bitmap的context
- // 并把它设置成为当前正在使用的context
- UIGraphicsBeginImageContext(size);
- // 绘制改变大小的图片
- [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
- // 从当前context中创建一个改变大小后的图片
- UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
- // 使当前的context出堆栈
- UIGraphicsEndImageContext();
- // 返回新的改变大小后的图片
-
- // NSData *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
- return scaledImage;
- }
- +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size
- {
-
-
-
- //UIImage *image=[UIImage imageNamed:@"xxoo.jpeg"];
- NSData *imageData=UIImageJPEGRepresentation(image, 1.f);
-
- if(size>imageData.length/1024)
- return image;
-
- // CGFloat size=40.f;// kb
- CGFloat scale=size/(imageData.length/1024);
-
- scale = sqrt (scale);
-
- CGSize newsize=image.size;
- newsize.height = newsize.height*scale;
- newsize.width = newsize.width*scale;
-
- return [RAUtils scaleToSize:image size:newsize];
- // NSData *newData=UIImageJPEGRepresentation(image, scale);
-
- // UIImage* ret= [[UIImage alloc] initWithData:newData];
- //
- // return ret;
- }
- +(NSString*) FloatFormat:(float)value
- {
- if (fmodf(value, 1)==0)
- {
-
- return [NSString stringWithFormat:@"%.0f",value];
-
- } else if (fmodf(value*10, 1)==0)
- {
-
- return [NSString stringWithFormat:@"%.1f",value];
-
- }
- else if (fmodf(value*100, 1)==0)
- {
-
- return [NSString stringWithFormat:@"%.2f",value];
-
- }
- else if (fmodf(value*1000, 1)==0)
- {
-
- return [NSString stringWithFormat:@"%.3f",value];
-
- }
- else
- {
-
- return [NSString stringWithFormat:@"%.4f",value];
-
-
- }
- return nil;
- }
- +(UIViewController*) getViewController:(UIView*) view
- {
- for (UIView* next = [view superview]; next; next = next.superview) {
- UIResponder* nextResponder = [next nextResponder];
- if ([nextResponder isKindOfClass:[UIViewController class]]) {
- return (UIViewController*)nextResponder;
- }
- }
- return nil;
- }
- + (float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
- {
- NSFileManager *fileManager = [[NSFileManager alloc] init];
- float size =0;
- NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
- for(int i = 0; i<[array count]; i++)
- {
- NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
- BOOL isDir;
- if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
- {
- NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
- size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
- }
- else
- {
- size+=[self fileSizeForDir:fullPath];
- }
- }
- return size;
- }
- /*创建错误信息字典*/
- +(NSDictionary*) error_dict:(NSError*)error
- {
-
- if(error==nil)
- return nil;
- NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
- [ret setValue:[NSString stringWithFormat:@"%ld",(long)error.code] forKey:@"error_code"];
- [ret setValue:error.domain forKey:@"err_domain"];
- [ret setValue:[error localizedDescription] forKey:@"err_message"];
- // [ret setObject:error.userInfo forKey:@"user_info"];
- return ret;
- }
- +(NSString*) current_date
- {
- NSDate * date = [NSDate date];
- NSTimeInterval sec = [date timeIntervalSinceNow];
- NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
-
- NSDateFormatter * df = [[NSDateFormatter alloc] init ];
- [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
- NSString * na = [df stringFromDate:currentDate];
- return na;
- }
- +(NSString*) current_date_time
- {
- NSDate * date = [NSDate date];
- NSTimeInterval sec = [date timeIntervalSinceNow];
- NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
-
- NSDateFormatter * df = [[NSDateFormatter alloc] init ];
- [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
- NSString * na = [df stringFromDate:currentDate];
- return na;
- }
- +(NSString*) current_date_forfile
- {
- NSDate * date = [NSDate date];
- NSTimeInterval sec = [date timeIntervalSinceNow];
- NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
-
- NSDateFormatter * df = [[NSDateFormatter alloc] init ];
- [df setDateFormat:@"MM_dd_yyyy_HH_mm_ss"];
- NSString * na = [df stringFromDate:currentDate];
- return na;
- }
- //+(void) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
- //{
- // if(title==nil)
- // title = @"Message";
- // if ([title isEqualToString:@"Add To Cart"]) {
- // if ([msg hasPrefix:@"Out of Stock.\n"]) {
- // title = @"Add To Cart: Out of Stock";
- // msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
- // }
- // }
- //
- //
- //
- // return [self alert_view:msg title:title];
- ////
- ////
- //// UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
- //// //block代码块取代了delegate
- ////
- ////
- //// // [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
- //// // textField.text = self.save_name;
- //// //
- //// //
- //// // }];
- ////
- //// // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
- //// //
- //// // UIAlertController * waitalert = [RAUtils waiting_alert:self title:@"Delete Order"];
- //// // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- //// //
- //// // NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
- //// //
- //// // dispatch_async(dispatch_get_main_queue(), ^{
- //// // [waitalert dismissViewControllerAnimated:YES completion:nil];
- //// //
- //// //
- //// // if([[return_json valueForKey:@"result"] intValue]==2)
- //// // {
- //// //
- //// // [RAUtils error_alert:nil title:@"Order Delete"] ;
- //// // }
- //// // else
- //// // {
- //// // [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
- //// // }
- //// //
- //// //
- //// //
- //// //
- //// // });
- //// // });
- //// //
- //// //
- //// // }];
- ////
- //// UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
- //// //DebugLog(@"Cancel");
- //// }];
- //// // [alertControl addAction:actionOne];
- ////
- //// [alertControl addAction:alertthree];
- ////
- ////
- //// UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
- //// }];
- //// [alertControl addAction:alertcancel];
- //// //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
- ////
- ////
- ////
- ////
- //// [vc presentViewController:alertControl animated:YES completion:nil];
- ////
- ////
- ////
- //// return;
- ////
- ////
- //
- //
- //}
- //+(void) alert_view :(NSString*) msg title:(NSString*) title
- //{
- // if(title==nil)
- // title = NSLocalizedString(@"Message", @"Message");
- // if(msg.length>0)
- // {
- // title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
- // }
- // UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", @"Ok") otherButtonTitles:nil, nil];
- // [alert show];
- //}
- + (long long) freeDiskSpaceInMegaBytes{
- struct statfs buf;
- long long freespace = -1;
- if(statfs("/var", &buf) >= 0){
- freespace = (long long)(buf.f_bsize * buf.f_bfree);
- }
- DebugLog(@"手机剩余存储空间为:%qi MB" ,freespace/1024/1024);
- return freespace/1024/1024;
- }
- //+(UIAlertController*) waiting_alert:(UIViewController*)parent title:(NSString*) title
- //{
- // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
- //
- //// [parent presentModalViewController:alertController animated:YES];
- // [parent presentViewController:alertController animated:YES completion:nil];
- // return alertController;
- //
- //}
- +(UIAlertController*) waiting_alert:(UIViewController*)parent title:(NSString*) title completion:(void (^ __nullable)(void))completion
- {
-
- return [self waiting_alert:parent message:@"Please wait..." title:title completion:completion];
- // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
- //
- // [parent presentViewController:alertController animated:YES completion:completion];
- // return alertController;
- }
- +(PopWaitAlert*) waiting_pop:(nullable NSString*) title completion:(void (^ __nullable)(void))completion
- {
-
-
- return [PopWaitAlert Show:title message:@"Please wait..." completion:completion];
-
- // return [self waiting_alert:parent message:@"Please wait..." title:title completion:completion];
- // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
- //
- // [parent presentViewController:alertController animated:YES completion:completion];
- // return alertController;
- }
- +(MessageBox*) message_box:(nullable NSString*) title message:(nullable NSString*)message completion:(void (^ __nullable)(void))completion
- {
-
-
- return [MessageBox Show:title message:message completion:completion];
-
- // return [self waiting_alert:parent message:@"Please wait..." title:title completion:completion];
- // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"Please wait..." preferredStyle:UIAlertControllerStyleAlert];
- //
- // [parent presentViewController:alertController animated:YES completion:completion];
- // return alertController;
- }
- //+(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title
- //{
- // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
- // [parent presentViewController:alertController animated:YES completion:nil];
- // return alertController;
- //
- //}
- +(UIAlertController*) waiting_alert:(UIViewController*)parent message:(NSString*)msg title:(NSString*) title completion:(void (^ __nullable)(void))completion
- {
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
- [parent presentViewController:alertController animated:YES completion:completion];
- NSLog(@"show waiting alert %p",alertController);
- return alertController;
- }
- +(void) playSound:(NSString*) name type:(NSString*) type
- {
-
- CFStringRef cfname = (__bridge CFStringRef)name;
- CFStringRef cftype = (__bridge CFStringRef)type;
- CFBundleRef mainBundle;
- SystemSoundID soundFileObject;
- mainBundle = CFBundleGetMainBundle ();
- CFURLRef soundFileURLRef = CFBundleCopyResourceURL (
- mainBundle,
- cfname,
- cftype,
- NULL
- );
- AudioServicesCreateSystemSoundID (
- soundFileURLRef,
- &soundFileObject
- );
- AudioServicesPlaySystemSound(soundFileObject);
- }
- +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc
- {
- if(title==nil)
- title = @"Message";
- if ([title isEqualToString:@"Add To Cart"]) {
- if ([msg hasPrefix:@"Out of Stock.\n"]) {
- title = @"Add To Cart: Out of Stock";
- msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
- }
- }
-
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
- [alertController addAction:action_0];
- [vc presentViewController:alertController animated:YES completion:nil];
- NSLog(@"show message alert %p",alertController);
- return alertController;
- }
- +(UIAlertController*) message_alert :(NSString*) msg title:(NSString*) title controller:(UIViewController*) vc action_handler:(void (^ __nullable)(UIAlertAction *action))action_handler completion:(void (^ __nullable)(void))completion
- {
- if(title==nil)
- title = @"Message";
- if ([title isEqualToString:@"Add To Cart"]) {
- if ([msg hasPrefix:@"Out of Stock.\n"]) {
- title = @"Add To Cart: Out of Stock";
- msg = [msg substringFromIndex:[@"Out of Stock.\n" length]];
- }
- }
-
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *action_0 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:action_handler];
- [alertController addAction:action_0];
- [vc presentViewController:alertController animated:YES completion:completion];
- NSLog(@"show message alert %p",alertController);
- return alertController;
- }
- //+(UIAlertView * ) waiting_alert :(NSString*) msg title:(NSString*) title
- //{
- // if(title==nil)
- // title = @"Please Wait";
- // if(msg==nil)
- // msg= @"Waiting...";
- // NSAssert(msg!=nil, @"error message from json is nil");
- // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
- // [alert show];
- // //
- // //
- // // UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
- // // aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
- // // // check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
- // //// if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
- // //// [alert setValue:aiView forKey:@"accessoryView"];
- // //// }else{
- // //// [alert addSubview:aiView];
- // //// }
- // //
- // // aiView.hidden = false;
- // // aiView.hidesWhenStopped = false;
- // // [aiView startAnimating];
- // //
- // //[alert addSubview:aiView];
- //
- // return alert;
- // //return nil;
- // // return alert;
- // // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
- // //[alert show];
- //}
- +(NSDictionary*) device_info
- {
-
-
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
- NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
- NSString* versionNum = [NSString stringWithFormat:@"Version: %@ Build %@",version,build];
-
- NSMutableDictionary * info = [[NSMutableDictionary alloc]init];
- [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
- [info setValue:[[UIDevice currentDevice] systemVersion] forKey:@"systemVersion"];
- [info setValue:[[UIDevice currentDevice] model] forKey:@"model"];
- [info setValue:versionNum forKey:@"ver"];
- [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
-
- return info;
- // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
- // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
- // [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
-
- }
- + (NSString *)deviceID {
- UIDevice * dev = [UIDevice currentDevice];
- NSUUID* uuid =dev.identifierForVendor;
- return uuid.UUIDString;
- }
- //+(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
- //{
- // NSArray *stringArray = [string componentsSeparatedByString:separator];
- //
- // return stringArray;
- //}
- +(NSDictionary*) string2dict:(NSString*) str
- {
-
- if(str==nil)
- return nil;
- NSError *error = nil;
- NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
- options: NSJSONReadingMutableContainers
- error: &error];
- DebugLog(@"%@",string2dic);
- return string2dic;
- }
- +(UIColor*) strColor:(NSString*) color
- {
- if([color.lowercaseString isEqualToString:@"red"])
- return [UIColor redColor];
-
- return [UIColor blackColor];
- }
- +(NSString*) base64en:(NSString*) string
- {
-
- if(string == nil)
-
- return nil;
-
- NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
- NSString *stringBase64 = [data base64EncodedStringWithOptions:0]; // base64格式的字符串
-
- return stringBase64;
- }
- +(NSString*) base64de:(NSString*) stringBase64
- {
-
- if(stringBase64==nil)
- return nil;
- NSData *data = [[NSData alloc] initWithBase64EncodedString:stringBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
- NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- return string;
- }
- +(void) deletefiles :(NSString*) path
- {
-
- // NSString *extension = @"m4r";
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- // NSString *documentsDirectory = [paths objectAtIndex:0];
-
- NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
- NSEnumerator *e = [contents objectEnumerator];
- NSString *filename;
- while ((filename = [e nextObject])) {
-
- bool result= [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
-
- if(!result)
- DebugLog(@"delete file failed %@------%@",path,filename);
- }
- }
- +(NSMutableArray*)dictionary2array:(NSDictionary*)json count_fields:(NSString*) count_fields item_mark:(NSString*) item_mark items_mark:(NSString* )items_mark
- {
- if(json==nil)
- return nil;
- NSMutableArray* ret = [[NSMutableArray alloc] init];
-
- int count = [[json valueForKey:count_fields] intValue];
-
- NSDictionary* items = nil;
- if(items_mark==nil)
- items = json;
- else
- items = [json objectForKey:items_mark];
- for(int i=0;i<count;i++)
- {
- NSDictionary* obj = [items objectForKey:[NSString stringWithFormat:@"%@%d",item_mark,i]];
- [ret addObject:obj];
- }
- return ret;
- }
- +(NSDictionary*) error_json :(int)code err_msg:(NSString*)msg
- {
-
- NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
- //#define RESULT_FALSE 0
- //#define RESULT_TRUE 2
- //#define RESULT_NET_ERROR -3
- //#define RESULT_NET_NOTAVAILABLE -4
- //#define RESULT_ERROR -5
- //#define RESULT_LOCALFILE_ERROR -7
- //#define RESULT_USERAUTH_ERROR -9
- //#define RESULT_UPDATE_USERAUTH_ERROR -11
- //#define RESULT_SESSION_EXPIRED -13
- //#define RESULT_VER_LOW
-
- if(msg.length<=0)
- {
- switch (code) {
- case RESULT_NET_NOTAVAILABLE:
- msg= MSG_NET_NOTAVAILABLE;
- break;
-
- default:
- // assert(@"UNDEFINE ERROR CODE!");
- break;
- }
- }
- // if(code==RESULT_NET_NOTAVAILABLE)
- // [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
- // else
- [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
- [ret setValue:msg forKey:@"err_msg"];
-
- // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
- // options:0
- // error:nil];
-
- return ret;
- }
- + (BOOL)isNumeric:(NSString*)string{
- NSScanner* scan = [NSScanner scannerWithString:string];
- int val;
- return[scan scanInt:&val] && [scan isAtEnd];
- }
- + (CGRect)relativeFrame:(CGRect) frame FromView:(UIView *)v toView:(UIView*)tv
- {
- return [v convertRect: frame toView:tv];
- }
- + (CGRect)relativeFrameForScreenWithView:(UIView *)v
- {
- UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
- CGRect rect=[v convertRect: v.bounds toView:window];
- return rect;
-
-
- // BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
- //
- // CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
- // if (!iOS7) {
- // screenHeight -= 20;
- // }
- // UIView *view = v;
- // CGFloat x = .0;
- // CGFloat y = .0;
- // while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
- // x += view.frame.origin.x;
- // y += view.frame.origin.y;
- // view = view.superview;
- // if ([view isKindOfClass:[UIScrollView class]]) {
- // x -= ((UIScrollView *) view).contentOffset.x;
- // y -= ((UIScrollView *) view).contentOffset.y;
- // }
- // }
- // return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
- }
- + (BOOL)saveData:(NSData *)data toPath:(NSString *)path {
- // NSString *directory = [path stringByDeletingLastPathComponent];
- NSFileManager *manager = [NSFileManager defaultManager];
- NSString *dir = [path stringByDeletingLastPathComponent];
- BOOL create = [manager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
- if (create) {
- BOOL save = [manager createFileAtPath:path contents:data attributes:nil];
- if (save) {
- return YES;
- }
- return NO;
- }
- return NO;
-
- }
- + (void)removeFileAtPath:(NSString *)path {
- if (!path.length) {
- return;
- }
- NSFileManager *manager = [NSFileManager defaultManager];
- [manager removeItemAtPath:path error:nil];
- }
- + (NSString *)appCacheDirectory {
- return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
- }
- +(NSString*)md5WithFile:(NSString*)path
- {
- return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
- }
- CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
- // Declare needed variables
- CFStringRef result = NULL;
- CFReadStreamRef readStream = NULL;
- // Get the file URL
- CFURLRef fileURL =
- CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
- (CFStringRef)filePath,
- kCFURLPOSIXPathStyle,
- (Boolean)false);
- if (!fileURL) goto done;
- // Create and open the read stream
- readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
- (CFURLRef)fileURL);
- if (!readStream) goto done;
- bool didSucceed = (bool)CFReadStreamOpen(readStream);
- if (!didSucceed) goto done;
- // Initialize the hash object
- CC_MD5_CTX hashObject;
- CC_MD5_Init(&hashObject);
- // Make sure chunkSizeForReadingData is valid
- if (!chunkSizeForReadingData) {
- chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
- }
- // Feed the data to the hash object
- bool hasMoreData = true;
- while (hasMoreData) {
- uint8_t buffer[chunkSizeForReadingData];
- CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
- if (readBytesCount == -1) break;
- if (readBytesCount == 0) {
- hasMoreData = false;
- continue;
- }
- CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
- }
- // Check if the read operation succeeded
- didSucceed = !hasMoreData;
- // Compute the hash digest
- unsigned char digest[CC_MD5_DIGEST_LENGTH];
- CC_MD5_Final(digest, &hashObject);
- // Abort if the read operation failed
- if (!didSucceed) goto done;
- // Compute the string result
- char hash[2 * sizeof(digest) + 1];
- for (size_t i = 0; i < sizeof(digest); ++i) {
- snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
- }
- result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
-
- done:
- if (readStream) {
- CFReadStreamClose(readStream);
- CFRelease(readStream);
- }
- if (fileURL) {
- CFRelease(fileURL);
- }
- return result;
- }
- + (BOOL)fileExistsAtPath:(NSString *)path {
-
- NSFileManager *fm = [NSFileManager defaultManager];
-
- return [fm fileExistsAtPath:path];
-
- return NO;
- }
- + (NSString *)htmlForVideo:(NSString*) iframeCode template:(NSString*) path
- {
-
- if(path==nil)
- path=[[NSBundle mainBundle] pathForResource:@"photostack_video" ofType:@"html"];
- NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
-
- if(tempate==nil)
- return @"";
-
- // NSData *imageData = UIImageJPEGRepresentation(image,1.0);
- // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
- // imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
-
-
- tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:iframeCode];
-
- return tempate;
- }
- + (NSString *)htmlForImage:(UIImage *)image template:(NSString*) path
- {
-
- if(path==nil)
- path=[[NSBundle mainBundle] pathForResource:@"photostack_image" ofType:@"html"];
- NSString* tempate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
-
- if(tempate==nil)
- return @"";
-
- NSData *imageData = UIImageJPEGRepresentation(image,1.0);
- // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
- NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
- imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
-
-
- tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:imageSource];
-
- return tempate;
- }
- + (nullable NSString *)md5:(nullable NSString *)str {
- if (!str) return nil;
-
- const char *cStr = str.UTF8String;
- unsigned char result[CC_MD5_DIGEST_LENGTH];
- CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
-
- NSMutableString *md5Str = [NSMutableString string];
- for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
- [md5Str appendFormat:@"%02x", result[i]];
- }
- return md5Str;
- }
- + (void)ra_showAlertTitle:(NSString *)title message:(NSString *)msg withViewController:(UIViewController *)vc {
-
- if (vc) {
- UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
-
- }];
-
- [alertVC addAction:okAction];
-
- [vc presentViewController:alertVC animated:YES completion:nil];
- NSLog(@"show alerttitle alert %p",alertVC);
- }
-
- }
- + (CGSize)sizeWithFont:(NSString*)string font:(UIFont *)font constrainedToSize:(CGSize)maxsize lineBreakMode:(NSLineBreakMode)lineBreakMode
- {
-
- if(string.length==0)
- return CGSizeZero;
- // Let's make an NSAttributedString first
- NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
- //Add LineBreakMode
- NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
- [paragraphStyle setLineBreakMode:lineBreakMode];
- [attributedString setAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, attributedString.length)];
- // Add Font
- [attributedString setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, attributedString.length)];
- //Now let's make the Bounding Rect
- CGSize expectedSize = [attributedString boundingRectWithSize:maxsize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
-
- return expectedSize;
- }
- + (BOOL) validateEmail:(NSString *)email
- {
- NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
- NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
- NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
- NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
- return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
- }
- + (BOOL)checkPassword:(NSString *) password
- {
- NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,16}";
- // NSString *pattern1 = @"^(?=.*)(?=.*[a-z])(?=.*[~!@#$%^&*:;,.=?$\x22]).{8,16}$";
- NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
- // NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern1];
-
- BOOL isMatch = [pred evaluateWithObject:password];//||[pred evaluateWithObject:password];
- return isMatch;
-
- }
- + (UIViewController *)getCurrentVC
- {
- UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
-
- UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
-
- return currentVC;
- }
- + (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
- {
- UIViewController *currentVC;
-
- if ([rootVC presentedViewController]) {
- // 视图是被presented出来的
-
- rootVC = [rootVC presentedViewController];
- }
- if ([rootVC isKindOfClass:[UITabBarController class]]) {
- // 根视图为UITabBarController
-
- currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
-
- } else if ([rootVC isKindOfClass:[UINavigationController class]]){
- // 根视图为UINavigationController
-
- currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
-
- } else {
- // 根视图为非导航类
-
- currentVC = rootVC;
- }
-
- return currentVC;
- }
- @end
|