| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960 |
- //
- // 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 "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 "ZipArchive.h"
- #define FileHashDefaultChunkSizeForReadingData 1024*8
- @implementation RAUtils
- +(NSString*) getdbzip
- {
-
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
- NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
-
-
- NSString* temp = NSTemporaryDirectory();
-
- NSString* uuid=[[NSUUID UUID] UUIDString];
-
- NSString *tempfile = [temp stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",uuid]];
-
- ZipArchive* zip = [[ZipArchive alloc] init];
-
-
- BOOL result = [zip CreateZipFile2:tempfile Password:@"usai2010"];
-
- result = [zip addFileToZip:database_path newname:[database_path lastPathComponent]];
- return tempfile;
-
-
- }
- +(NSData*) getdbfile
- {
- 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];
-
- NSError *error = nil;
- NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
- options: NSJSONReadingMutableContainers
- error: &error];
- // DebugLog(@"%@",string2dic);
- return string2dic;
-
- }
- + (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:nil error:nil];
-
- NSTextCheckingResult *match = [regex firstMatchInString:content options:nil 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:nil error:nil];
-
- NSArray *matches = [regex matchesInString:content options:nil 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:@"%d",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;
- }
- +(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) {
- // //
- // // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" 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 dismissWithClickedButtonIndex:0 animated:FALSE];
- // //
- // //
- // // 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 = @"Message";
- if(msg.length>0)
- {
- title=[NSString stringWithFormat:@"%@\n\n%@",title,msg];
- }
- UIAlertView * alert = [[UIAlertView alloc] initWithTitle: title message:nil delegate:nil cancelButtonTitle:@"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;
- }
- +(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"];
-
- }
- +(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator
- {
- NSArray *stringArray = [string componentsSeparatedByString:separator];
-
- return stringArray;
- }
- +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim
- {
- if(arr.count==0)
- return nil;
- NSMutableArray * marr = [arr mutableCopy];
-
- begin:
- for (NSString* item in marr) {
- if(item.length==0 )
- if( btrim)
- {
-
- [marr removeObject:item];
- goto begin;
- }
-
- }
- NSString * ret = [marr componentsJoinedByString:separator];
- return ret;
- }
- +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets
- {
- if(brackets!=nil)
- separator = [NSString stringWithFormat:@"%@%@%@",brackets,separator,brackets];
- NSMutableArray * marr = [arr mutableCopy];
- begin:
- for (NSString* item in marr) {
- if(item.length==0 )
- if( btrim)
- {
-
- [marr removeObject:item];
- goto begin;
- }
-
-
-
- }
- NSString * ret = [marr componentsJoinedByString:separator];
-
- if(brackets!=nil)
- ret = [NSString stringWithFormat:@"%@%@%@",brackets,ret,brackets];
-
- return ret;
- }
- +(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];
- }
- +(NSData*) dict2data:(NSDictionary*) dict
- {
- if(dict==nil)
- return nil;
- // 将NSDictionary转化为NSData
- NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
- return data;
- }
- +(NSString*) dict2string:(NSDictionary*) dict
- {
-
- if(dict==nil)
- return nil;
-
- // 将NSDictionary转化为NSData
- NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
-
- // 再将NSData转为字符串
- NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
-
- return jsonStr;
- }
- +(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;
- }
- + (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]];
- imageSource=[NSString stringWithFormat:@"<img src = \"%@\" />", imageSource];
-
-
- tempate= [tempate stringByReplacingOccurrencesOfString:@"##replacement##" withString:imageSource];
-
- return tempate;
- }
- @end
|