转发一篇别人的方法文章

转载一篇别人的文章,iOS常用的方法,至于是谁的,我忘记了,手快点掉了。。


引入的头文件

#import "sys/utsname.h" //手机运行内存

.h文件

+ (int64_t)memoryUsage;// 获得当前 App 的内存占用情况

+ (double)availableMemory;//当前设备可用内存

+ (double)usedMemory;//当前任务所占内存

/*

 手机型号

 */

+(NSString*)deviceVersion;

/*

 判断字典中是否包含该字段  并判断改字段是否是想要的类型

 */

+ (BOOL)allDataContainsObject:(NSDictionary*)allDict KeyStr:(NSString*)key type:(__unsafe_unretainedClass)typeClass;

/*

 json字典转字符串方法

 */

+(NSString*)convertToJsonDict:(NSDictionary*)dict;

/*

 字典转化字符串

 */

+(NSString*)dictionaryToJson:(NSDictionary*)dict;

/*

 字符串转字典

 */

+ (NSDictionary*)dictionaryWithJsonString:(NSString*)jsonString;

/*

 获取当前时间戳

 */

+ (NSString*)currentTimeSts:(NSString*)formatType;

/*

 获取当前时间

 */

+ (NSString*)currentDateFormat:(NSString*)dateFormat;

/*

 时间戳转时间(字符串)  如:getShowDateWithTime:_model.input_time dateFormat:@"yyyy.MM.dd"];

 */

+ (NSString*)getShowDateWithTime:(NSString*)time dateFormat:(NSString*)dateFormat;

/*

 获取当前时间的: 前一周(day:-7)丶前一个月(month:-30)丶前一年(year:-1)的时间戳 或时间

 */

+ (NSString*)ddpGetExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day dateFormat:(NSString*)dateFormat isDateStr:(BOOL)isDateStr;

/*

 时间(data)转时间(字符串)  如:

 */

+ (NSString*)getShowDate:(NSDate*)date dateFormat:(NSString*)dateFormat;

/*

 时间(字符串)转时间戳 如:2017-4-10 17:15:10

 */

+ (NSString*)getTimeStrWithString:(NSString*)str dateFormat:(NSString*)dateFormat;

/*

 计算两个时间戳的时间差

 */

+ (NSString*)compareTwoTime:(longlong)time1 time2:(longlong)time2;

/*

 生成当前时间字符串

 */

+ (NSString*)GetCurrentTimeString;

+ (NSString*)GetCurrentTimeStringVideoDataPath;

+ (NSString*)GetCurrentTimeStringm_y_h_m;

/*

 拍照的照片会自动旋转90度  因为大于2M

 */

+ (UIImage *)fixOrientation:(UIImage *)aImage;

/*

 保存图片

 */

+ (BOOL)saveImage:(UIImage *)imgs imageNames:(NSString*)imageName;

/*

 读取图片

 */

+ (NSString*)upDataImages:(NSString*)imageName;

/*

 删除图片

 */

+(BOOL)removeImages;

/*

 根据产品ID返回产品名字

 */

+ (NSString*)upProImgProId:(NSString*)proId isSele:(BOOL)isSele;

/*

 获取颜色数组

 */

+ (NSArray*)getColorArray;

/*

 下载文件的路径  folderName 文件夹名字 fillName文件名字  fillType文件类型

 */

+ (NSString*)createFillePathFolderName:(NSString*)folderName filleName:(NSString*)fillName filleType:(NSString*)fillType isRemoveFill:(BOOL)isRemove;

/*

 获取下载文件的路径  folderName文件夹名字 fillNameType文件名字+后缀(文件类型) isFille是否取文件  yes取文件 no取文件夹

 */

+ (NSString*)getFillePathFolderName:(NSString*)folderName fillNameType:(NSString*)fillNameType isFille:(BOOL)isFille;

/*

 该路径下是否存在该文件  folderName 文件夹名字 fillName文件名字  fillType文件类型

 */

+ (BOOL)isHaveFillePathFolderName:(NSString*)folderName filleName:(NSString*)fillName filleType:(NSString*)fillType;

/*

 获取文件夹下所有文件的信息 fillPath文件夹路径 isascending是否升序 yes升序 no降序

 */

+ (NSMutableArray*)visitDirectoryList:(NSString*)fillPath Isascending:(BOOL)isascending;

.m文件

// 获得当前 App 的内存占用情况

+ (int64_t)memoryUsage {

    int64_tmemoryUsageInByte =0;

    task_vm_info_data_t vmInfo;

    mach_msg_type_number_t count = TASK_VM_INFO_COUNT;

    kern_return_tkernelReturn =task_info(mach_task_self(),TASK_VM_INFO, (task_info_t) &vmInfo, &count);

if(kernelReturn ==KERN_SUCCESS) {

        memoryUsageInByte = (int64_t) vmInfo.phys_footprint;

        BRYLog(@"获得当前 App 的内存占用情况Memory in use (in bytes): %f MB", memoryUsageInByte/1000.0/1000.0);

}else{

        BRYLog(@"获得当前 App 的内存占用情况Error with task_info(): %s", mach_error_string(kernelReturn));

    }

returnmemoryUsageInByte;

}

//当前设备可用内存

+ (double)availableMemory{

    vm_statistics_data_t vmStats;

    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;

    kern_return_tkernReturn =host_statistics(mach_host_self(),HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);

if(kernReturn !=KERN_SUCCESS) {

returnNSNotFound;

    }

    BRYLog(@"当前设备可用内存:%fMB",((vm_page_size *vmStats.free_count) /1024.0) /1024.0);

return((vm_page_size*vmStats.free_count) /1024.0) /1024.0;

}

//当前任务所占内存

+ (double)usedMemory{

    task_basic_info_data_t taskInfo;

    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;

    kern_return_tkernReturn =task_info(mach_task_self(),TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);

if(kernReturn !=KERN_SUCCESS) {

returnNSNotFound;

    }

    BRYLog(@"当前任务所占内存:%fMB",taskInfo.resident_size /1024.0/1024.0);

returntaskInfo.resident_size/1024.0/1024.0;

}

/*

 手机型号

 */

+(NSString*)deviceVersion{

// 需要#import "sys/utsname.h"

structutsnamesystemInfo;

    uname(&systemInfo);

    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

if([deviceModelisEqualToString:@"iPhone3,1"])return@"iPhone 4";

if([deviceModelisEqualToString:@"iPhone3,2"])return@"iPhone 4";

if([deviceModelisEqualToString:@"iPhone3,3"])return@"iPhone 4";

if([deviceModelisEqualToString:@"iPhone4,1"])return@"iPhone 4S";

if([deviceModelisEqualToString:@"iPhone5,1"])return@"iPhone 5";

if([deviceModel isEqualToString:@"iPhone5,2"])return@"iPhone 5 (GSM+CDMA)";

if([deviceModel isEqualToString:@"iPhone5,3"])return@"iPhone 5c (GSM)";

if([deviceModel isEqualToString:@"iPhone5,4"])return@"iPhone 5c (GSM+CDMA)";

if([deviceModel isEqualToString:@"iPhone6,1"])return@"iPhone 5s (GSM)";

if([deviceModel isEqualToString:@"iPhone6,2"])return@"iPhone 5s (GSM+CDMA)";

if([deviceModelisEqualToString:@"iPhone7,1"])return@"iPhone 6 Plus";

if([deviceModelisEqualToString:@"iPhone7,2"])return@"iPhone 6";

if([deviceModelisEqualToString:@"iPhone8,1"])return@"iPhone 6s";

if([deviceModel isEqualToString:@"iPhone8,2"])return@"iPhone 6s Plus";

if([deviceModelisEqualToString:@"iPhone8,4"])return@"iPhone SE";

// 日行两款手机型号均为日本独占,可能使用索尼FeliCa支付方案而不是苹果支付

if([deviceModelisEqualToString:@"iPhone9,1"])return@"iPhone 7";

if([deviceModelisEqualToString:@"iPhone9,2"])return@"iPhone 7 Plus";

if([deviceModelisEqualToString:@"iPhone9,3"])return@"iPhone 7";

if([deviceModelisEqualToString:@"iPhone9,4"])return@"iPhone 7 Plus";

if([deviceModelisEqualToString:@"iPhone10,1"])return@"iPhone_8";

if([deviceModelisEqualToString:@"iPhone10,4"])return@"iPhone_8";

if([deviceModel isEqualToString:@"iPhone10,2"])return@"iPhone_8_Plus";

if([deviceModel isEqualToString:@"iPhone10,5"])return@"iPhone_8_Plus";

if([deviceModelisEqualToString:@"iPhone10,3"])return@"iPhone X";

if([deviceModelisEqualToString:@"iPhone10,6"])return@"iPhone X";

if([deviceModelisEqualToString:@"iPhone11,8"])return@"iPhone XR";

if([deviceModelisEqualToString:@"iPhone11,2"])return@"iPhone XS";

if([deviceModel isEqualToString:@"iPhone11,6"])return@"iPhone XS Max";

if([deviceModel isEqualToString:@"iPhone11,4"])return@"iPhone XS Max";

if([deviceModelisEqualToString:@"iPod1,1"])return@"iPod Touch 1G";

if([deviceModelisEqualToString:@"iPod2,1"])return@"iPod Touch 2G";

if([deviceModelisEqualToString:@"iPod3,1"])return@"iPod Touch 3G";

if([deviceModelisEqualToString:@"iPod4,1"])return@"iPod Touch 4G";

if([deviceModel isEqualToString:@"iPod5,1"])return@"iPod Touch (5 Gen)";

if([deviceModelisEqualToString:@"iPad1,1"])return@"iPad";

if([deviceModelisEqualToString:@"iPad1,2"])return@"iPad 3G";

if([deviceModelisEqualToString:@"iPad2,1"])return@"iPad 2 (WiFi)";

if([deviceModelisEqualToString:@"iPad2,2"])return@"iPad 2";

if([deviceModelisEqualToString:@"iPad2,3"])return@"iPad 2 (CDMA)";

if([deviceModelisEqualToString:@"iPad2,4"])return@"iPad 2";

if([deviceModelisEqualToString:@"iPad2,5"])return@"iPad Mini (WiFi)";

if([deviceModelisEqualToString:@"iPad2,6"])return@"iPad Mini";

if([deviceModel isEqualToString:@"iPad2,7"])return@"iPad Mini (GSM+CDMA)";

if([deviceModelisEqualToString:@"iPad3,1"])return@"iPad 3 (WiFi)";

if([deviceModelisEqualToString:@"iPad3,2"])return@"iPad 3 (GSM+CDMA)";

if([deviceModelisEqualToString:@"iPad3,3"])return@"iPad 3";

if([deviceModelisEqualToString:@"iPad3,4"])return@"iPad 4 (WiFi)";

if([deviceModelisEqualToString:@"iPad3,5"])return@"iPad 4";

if([deviceModelisEqualToString:@"iPad3,6"])return@"iPad 4 (GSM+CDMA)";

if([deviceModelisEqualToString:@"iPad4,1"])return@"iPad Air (WiFi)";

if([deviceModel isEqualToString:@"iPad4,2"])return@"iPad Air (Cellular)";

if([deviceModel isEqualToString:@"iPad4,4"])return@"iPad Mini 2 (WiFi)";

if([deviceModel isEqualToString:@"iPad4,5"])return@"iPad Mini 2 (Cellular)";

if([deviceModelisEqualToString:@"iPad4,6"])return@"iPad Mini 2";

if([deviceModelisEqualToString:@"iPad4,7"])return@"iPad Mini 3";

if([deviceModelisEqualToString:@"iPad4,8"])return@"iPad Mini 3";

if([deviceModelisEqualToString:@"iPad4,9"])return@"iPad Mini 3";

if([deviceModel isEqualToString:@"iPad5,1"])return@"iPad Mini 4 (WiFi)";

if([deviceModelisEqualToString:@"iPad5,2"])return@"iPad Mini 4 (LTE)";

if([deviceModelisEqualToString:@"iPad5,3"])return@"iPad Air 2";

if([deviceModelisEqualToString:@"iPad5,4"])return@"iPad Air 2";

if([deviceModelisEqualToString:@"iPad6,3"])return@"iPad Pro 9.7";

if([deviceModelisEqualToString:@"iPad6,4"])return@"iPad Pro 9.7";

if([deviceModelisEqualToString:@"iPad6,7"])return@"iPad Pro 12.9";

if([deviceModelisEqualToString:@"iPad6,8"])return@"iPad Pro 12.9";

if([deviceModelisEqualToString:@"AppleTV2,1"])return@"Apple TV 2";

if([deviceModelisEqualToString:@"AppleTV3,1"])return@"Apple TV 3";

if([deviceModelisEqualToString:@"AppleTV3,2"])return@"Apple TV 3";

if([deviceModelisEqualToString:@"AppleTV5,3"])return@"Apple TV 4";

if([deviceModelisEqualToString:@"i386"])return@"Simulator";

if([deviceModelisEqualToString:@"x86_64"])return@"Simulator";

returndeviceModel;

}

/*

 判断字典中是否包含该字段  并判断改字段是否是想要的类型

 */

+ (BOOL)allDataContainsObject:(NSDictionary*)allDict KeyStr:(NSString*)key type:(__unsafe_unretainedClass)typeClass{

if([[allDictallKeys]containsObject:key]) {

if([[allDictobjectForKey:key]isKindOfClass:typeClass]) {

returnYES;

}else{

returnNO;

        }

}else{

returnNO;

    }

}

/*

 json字典转字符串方法

 */

+(NSString*)convertToJsonDict:(NSDictionary*)dict{

    NSError*error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString*jsonString;

if(!jsonData) {

        FBLog(@"%@",error);

}else{

        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString*mutStr = [NSMutableStringstringWithString:jsonString];

    NSRangerange = {0,jsonString.length};

//去掉字符串中的空格

    [mutStrreplaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRangerange2 = {0,mutStr.length};

//去掉字符串中的换行符

    [mutStrreplaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

returnmutStr;

}

/*

 字典转化字符串

 */

+(NSString*)dictionaryToJson:(NSDictionary*)dict{

NSError*parseError =nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];

return[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

/*

 字符串转字典

 */

+ (NSDictionary*)dictionaryWithJsonString:(NSString*)jsonString{

if(jsonString ==nil) {

returnnil;

    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError*err;

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];

if(err) {

        FBLog(@"json解析失败:%@",err);

returnnil;

    }

returndict;

}

/*

 获取当前时间戳

 */

+ (NSString*)currentTimeSts:(NSString*)formatType{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

    [formattersetDateStyle:NSDateFormatterMediumStyle];

    [formattersetTimeStyle:NSDateFormatterShortStyle];

[formattersetDateFormat:formatType];// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

//设置时区,这个对于时间的处理有时很重要

    NSTimeZone* timeZone = [NSTimeZonetimeZoneWithName:@"Asia/Beijing"];

    [formattersetTimeZone:timeZone];

NSDate*datenow = [NSDatedate];//现在时间,你可以输出来看下是什么格式

NSString* timeSts = [NSStringstringWithFormat:@"%ld", (long)[datenowtimeIntervalSince1970]*1000];

returntimeSts;

}

/*

 获取当前时间

 */

+ (NSString*)currentDateFormat:(NSString*)dateFormat{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    dateFormatter.dateFormat= dateFormat ? dateFormat :@"yyyy-MM-dd HH:mm:ss";

// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

//设置时区,这个对于时间的处理有时很重要

    NSTimeZone* timeZone = [NSTimeZonetimeZoneWithName:@"Asia/Beijing"];

    [dateFormattersetTimeZone:timeZone];

//获取当前时间日期

    NSDate*date=[NSDatedate];

    NSString*dateStr=[dateFormatterstringFromDate:date];

    FBLog(@"%@",dateStr);

returndateStr;

}

/*

 时间戳转时间(字符串)  如:getShowDateWithTime:_model.input_time dateFormat:@"yyyy.MM.dd"];

 */

+ (NSString*)getShowDateWithTime:(NSString*)time dateFormat:(NSString*)dateFormat{

    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:[time longLongValue]];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    dateFormatter.dateFormat= dateFormat ? dateFormat :@"yyyy-MM-dd HH:mm:ss";

    NSString*timeStr = [dateFormatterstringFromDate:timeDate];

returntimeStr;

}

/*

 获取当前时间的: 前一周(day:-7)丶前一个月(month:-30)丶前一年(year:-1)的时间戳 或时间

 */

+ (NSString*)ddpGetExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day dateFormat:(NSString*)dateFormat isDateStr:(BOOL)isDateStr{

    NSDate*currentdata = [NSDatedate];

    ///< NSCalendar -- 日历类,它提供了大部分的日期计算接口,并且允许您在NSDate和NSDateComponents之间转换

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

/*

     ///<  NSDateComponents:时间容器,一个包含了详细的年月日时分秒的容器。

     ///< 下例:获取指定日期的年,月,日

     NSDateComponents *comps = nil;

     comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentdata];

     FBLog(@"年 year = %ld",comps.year);

     FBLog(@"月 month = %ld",comps.month);

     FBLog(@"日 day = %ld",comps.day);*/

    NSDateComponents *datecomps = [[NSDateComponents alloc] init];

    [datecompssetYear:year?:0];

    [datecompssetMonth:month?:0];

    [datecompssetDay:day?:0];

    ///< dateByAddingComponents: 在参数date基础上,增加一个NSDateComponents类型的时间增量

    NSDate*calculatedate = [calendardateByAddingComponents:datecompstoDate:currentdataoptions:0];

    ///< 打印推算时间

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formattersetDateFormat:dateFormat?:@"yyyy-MM-dd hh:mm:ss"];

    NSString*calculateStr = [formatterstringFromDate:calculatedate];

if(isDateStr ==YES) {//返回时间字符串

returncalculateStr;

    }

//返回时间戳

NSString*result = [NSStringstringWithFormat:@"%ld", (long)[calculatedatetimeIntervalSince1970]];

returnresult;

}

/*

 时间(data)转时间(字符串)  如:

 */

+ (NSString*)getShowDate:(NSDate*)date dateFormat:(NSString*)dateFormat{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    dateFormatter.dateFormat= dateFormat ? dateFormat :@"yyyy-MM-dd HH:mm:ss";

    NSString*timeStr = [dateFormatterstringFromDate:date];

returntimeStr;

}

/*

 时间(字符串)转时间戳 如:2017-4-10 17:15:10

 */

+ (NSString*)getTimeStrWithString:(NSString*)str dateFormat:(NSString*)dateFormat{

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象

[dateFormattersetDateFormat:dateFormat ? dateFormat :@"yyyy-MM-dd HH:mm:ss"];//设定时间的格式

NSDate*tempDate = [dateFormatterdateFromString:str];//将字符串转换为时间对象

NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]];//字符串转成时间戳,精确到毫秒*1000

returntimeStr;

}

/*

 计算两个时间戳的时间差

 */

+ (NSString*)compareTwoTime:(longlong)time1 time2:(longlong)time2{

    NSTimeIntervalbalance = time2 /1000- time1 /1000;

    NSString*timeString = [[NSStringalloc]init];

    timeString = [NSStringstringWithFormat:@"%f",balance /60];

    timeString = [timeStringsubstringToIndex:timeString.length-7];

    NSIntegertimeInt = [timeStringintValue];

    NSIntegerhour = timeInt /60;

    NSIntegermint = timeInt %60;

if(hour ==0) {

timeString = [NSStringstringWithFormat:@"%ld分钟",(long)mint];

}else{

if(mint ==0) {

timeString = [NSStringstringWithFormat:@"%ld小时",(long)hour];

}else{

timeString = [NSStringstringWithFormat:@"%ld小时%ld分钟",(long)hour,(long)mint];

        }

    }

returntimeString;

}

/*

 生成当前时间字符串

 */

+ (NSString*)GetCurrentTimeString{

    NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];

[dateformatsetDateFormat:@"YYYY-MM-dd hh:mm:ss"];//不能改

    NSString* strTime = [dateformatstringFromDate:[NSDatedate]];

if([strTimeisEqualToString:@""] || strTime ==nil) {

        NSMutableArray* dataArray = [[NSMutableArrayalloc]init];

for(inti =0; i <1; i++) {

intrandom =arc4random()%50;

            NSMutableString *str = [[NSMutableString alloc]init];

for(intj =0; j < random; j++) {

                [strappendString:@"adfsafdksanf"];

            }

            [dataArrayaddObject:str];

        }

        strTime = dataArray[0];

    }

returnstrTime;

}

+ (NSString*)GetCurrentTimeStringVideoDataPath{

    NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];

[dateformatsetDateFormat:@"YYYYMMddhhmmss"];//不能改

    NSString* strTime = [dateformatstringFromDate:[NSDatedate]];

if([strTimeisEqualToString:@""] || strTime ==nil) {

        NSMutableArray* dataArray = [[NSMutableArrayalloc]init];

for(inti =0; i <1; i++) {

intrandom =arc4random()%50;

            NSMutableString *str = [[NSMutableString alloc]init];

for(intj =0; j < random; j++) {

                [strappendString:@"adfsafdksanf"];

            }

            [dataArrayaddObject:str];

        }

        strTime = dataArray[0];

    }

returnstrTime;

}

+ (NSString*)GetCurrentTimeStringm_y_h_m{

    NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];

    [dateformatsetDateFormat:@"MM-dd hh:mm"];

    NSString* strTime = [dateformatstringFromDate:[NSDatedate]];

if([strTimeisEqualToString:@""] || strTime ==nil) {

        NSMutableArray* dataArray = [[NSMutableArrayalloc]init];

for(inti =0; i <1; i++) {

intrandom =arc4random()%50;

            NSMutableString *str = [[NSMutableString alloc]init];

for(intj =0; j < random; j++) {

                [strappendString:@"adfsafdksanf"];

            }

            [dataArrayaddObject:str];

        }

        strTime = dataArray[0];

    }

returnstrTime;

}

/*

 拍照的照片会自动旋转90度  因为大于2M

 */

+ (UIImage *)fixOrientation:(UIImage *)aImage {

// No-op if the orientation is already correct

if(aImage.imageOrientation == UIImageOrientationUp)

returnaImage;

// We need to calculate the proper transformation to make the image upright.

// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.

    CGAffineTransform transform = CGAffineTransformIdentity;

switch(aImage.imageOrientation) {

caseUIImageOrientationDown:

caseUIImageOrientationDownMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);

            transform = CGAffineTransformRotate(transform,M_PI);

break;

caseUIImageOrientationLeft:

caseUIImageOrientationLeftMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width,0);

            transform = CGAffineTransformRotate(transform,M_PI_2);

break;

caseUIImageOrientationRight:

caseUIImageOrientationRightMirrored:

            transform = CGAffineTransformTranslate(transform,0, aImage.size.height);

            transform = CGAffineTransformRotate(transform, -M_PI_2);

break;

default:

break;

    }

switch(aImage.imageOrientation) {

caseUIImageOrientationUpMirrored:

caseUIImageOrientationDownMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.width,0);

            transform = CGAffineTransformScale(transform, -1,1);

break;

caseUIImageOrientationLeftMirrored:

caseUIImageOrientationRightMirrored:

            transform = CGAffineTransformTranslate(transform, aImage.size.height,0);

            transform = CGAffineTransformScale(transform, -1,1);

break;

default:

break;

    }

// Now we draw the underlying CGImage into a new context, applying the transform

// calculated above.

CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,

                                             CGImageGetBitsPerComponent(aImage.CGImage),0,

                                             CGImageGetColorSpace(aImage.CGImage),

                                             CGImageGetBitmapInfo(aImage.CGImage));

    CGContextConcatCTM(ctx, transform);

switch(aImage.imageOrientation) {

caseUIImageOrientationLeft:

caseUIImageOrientationLeftMirrored:

caseUIImageOrientationRight:

caseUIImageOrientationRightMirrored:

// Grr...

            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);

break;

default:

            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);

break;

    }

// And now we just create a new UIImage from the drawing context

    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);

    UIImage *img = [UIImage imageWithCGImage:cgimg];

    CGContextRelease(ctx);

    CGImageRelease(cgimg);

returnimg;

}

/*

 保存图片

 */

+ (BOOL)saveImage:(UIImage *)imgs imageNames:(NSString*)imageName{

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:@"imageSave"];

// 获取tmp目录路径

//    NSString *savePath = NSTemporaryDirectory();

    NSFileManager *fileManager = [NSFileManager defaultManager];

BOOLisDir =FALSE;

BOOLisDirExist = [fileManagerfileExistsAtPath:savePathisDirectory:&isDir];

if(!(isDirExist && isDir)){

BOOLbCreateDir = [fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YESattributes:nilerror:nil];

if(!bCreateDir){

            FBLog(@"创建文件夹失败!");

        }

    }

    NSString*filleName = [NSStringstringWithFormat:@"%@%@",imageName,@".jpg"];

    NSString*fillDocsPath = [savePathstringByAppendingPathComponent:filleName];

BOOLresult =[UIImageJPEGRepresentation(imgs,1) writeToFile:fillDocsPath atomically:YES];// 保存成功会返回YES

if(result ==YES) {

        FBLog(@"\n图片保存成功::%@",fillDocsPath);

    }

returnYES;

}

/*

 读取图片

 */

+ (NSString*)upDataImages:(NSString*)imageName{

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:@"imageSave"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

BOOLisDir =FALSE;

BOOLisDirExist = [fileManagerfileExistsAtPath:savePathisDirectory:&isDir];

if(!(isDirExist && isDir)){

BOOLbCreateDir = [fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YESattributes:nilerror:nil];

if(!bCreateDir){

            FBLog(@"创建文件夹失败!");

        }

    }

    NSString*filleName = [NSStringstringWithFormat:@"%@%@",imageName,@".jpg"];

    NSString*fillDocsPath = [savePathstringByAppendingPathComponent:filleName];

    FBLog(@"\n读取图片路径::%@", fillDocsPath);

returnfillDocsPath;

}

/*

 删除图片

 */

+(BOOL)removeImages{

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:@"imageSave"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

BOOLisDir =FALSE;

BOOLisDirExist = [fileManagerfileExistsAtPath:savePathisDirectory:&isDir];

if(!(isDirExist && isDir)){

BOOLbCreateDir = [fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YESattributes:nilerror:nil];

if(!bCreateDir){

            FBLog(@"创建文件夹失败!");

        }

    }

if([[NSFileManager defaultManager] fileExistsAtPath:savePath]){

[[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];

returnYES;

}else{

returnNO;

    }

}

/*

 根据产品ID返回产品名字

 */

+ (NSString*)upProImgProId:(NSString*)proId isSele:(BOOL)isSele{

    NSString* proImgSre =@"";

if(FBNullString(proId)) {

returnproImgSre;

    }

//11:搜索、12:全部、13:进入群聊、1001:富巴三表、1002:财医体检、1003:历史轨迹挖掘机、1004:富巴概率计、1005:周期波冲浪板、1006:富巴价值锚、1007:富巴选股器、1008:工兵排雷、1009:发展望远镜、1010:增长透视镜、

    NSArray * idArr = @[@"1001",@"1002",@"1003",@"1004",@"1005",@"1006",@"1007",@"1008",@"1009",@"1010",@"12",@"13"];

    NSArray * imgArr = @[@"icon_fbsb",@"icon_cytj",@"icon_wjj",@"icon_glj",@"icon_clb",@"icon_jzm",@"icon_xgqs",@"icon_gbpls",@"icon_wyjs",@"icon_tsjs",@"icon_qb",@"icon_tgldz"];

[idArrenumerateObjectsUsingBlock:^(id_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {

        NSString* ids = obj;

if([proId  intValue] == [idsintValue]) {

            [FBNSUserDefaults setObject:imgArr[idx] forKey:@"proImgSre"];

*stop =YES;

        }

    }];

    proImgSre = [FBNSUserDefaults objectForKey:@"proImgSre"];

if(isSele ==NO) {

        proImgSre = [NSStringstringWithFormat:@"%@no",proImgSre];

    }

returnproImgSre;

}

/*

 获取颜色数组

 */

+ (NSArray*)getColorArray{

return@[@"#367EF6",@"#F66336",@"#F6BE36",@"#17C5AA",@"#A64AFC",@"#55C9FF",@"#F66BCD",@"#EE612C",@"#7f6000",@"#cccccc",@"#6aa84f",@"#ff0000",@"#dd7e6b",@"#274e13",@"#8EE5EE",@"#006600"];

}

/*

 下载文件的路径  folderName 文件夹名字 fillName文件名字  fillType文件类型

 */

+ (NSString*)createFillePathFolderName:(NSString*)folderName filleName:(NSString*)fillName filleType:(NSString*)fillType isRemoveFill:(BOOL)isRemove{

if(FBNullString(folderName)) {

        folderName =@"BRYDownLoadFolder";

    }

if(FBNullString(fillName)) {

        fillName =@"BRYDownLoadFille";

    }

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:folderName];

    NSFileManager *fileManager = [NSFileManager defaultManager];

BOOLisDir =FALSE;

BOOLisDirExist = [fileManagerfileExistsAtPath:savePathisDirectory:&isDir];

if(!(isDirExist && isDir)){

BOOLbCreateDir = [fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YESattributes:nilerror:nil];

if(!bCreateDir){

            FBLog(@"创建文件夹失败!");

        }

    }

    NSString*filleName = [NSStringstringWithFormat:@"%@%@",fillName,fillType];

    NSString*fillDocsPath = [savePathstringByAppendingPathComponent:filleName];

if([[NSFileManager defaultManager] fileExistsAtPath:fillDocsPath]){

if(isRemove ==YES) {

[[NSFileManager defaultManager] removeItemAtPath:fillDocsPath error:nil];

        }

    }

    FBLog(@"保存的沙河路径下的文件::::%@",fillDocsPath);

returnfillDocsPath;

}

/*

 获取下载文件的路径  folderName文件夹名字 fillNameType文件名字+后缀(文件类型) isFille是否取文件  yes取文件 no取文件夹

 */

+ (NSString*)getFillePathFolderName:(NSString*)folderName fillNameType:(NSString*)fillNameType isFille:(BOOL)isFille{

if(FBNullString(folderName)) {

        folderName =@"BRYDownLoadFolder";

    }

if(FBNullString(fillNameType)) {

        fillNameType =@"BRYDownLoadFille.pdf";

    }

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:folderName];

if(isFille ==NO) {

returnsavePath;

}else{

        NSString*fillDocsPath = [savePathstringByAppendingPathComponent:fillNameType];

returnfillDocsPath;

    }

}

/*

 该路径下是否存在该文件  folderName 文件夹名字 fillName文件名字  fillType文件类型

 */

+ (BOOL)isHaveFillePathFolderName:(NSString*)folderName filleName:(NSString*)fillName filleType:(NSString*)fillType{

if(FBNullString(folderName)) {

        folderName =@"BRYDownLoadFolder";

    }

if(FBNullString(fillName)) {

        fillName =@"BRYDownLoadFille";

    }

NSString *savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject] stringByAppendingPathComponent:folderName];

    NSFileManager *fileManager = [NSFileManager defaultManager];

BOOLisDir =FALSE;

BOOLisDirExist = [fileManagerfileExistsAtPath:savePathisDirectory:&isDir];

if(!(isDirExist && isDir)){

BOOLbCreateDir = [fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YESattributes:nilerror:nil];

if(!bCreateDir){

            FBLog(@"创建文件夹失败!");

        }

    }

    NSString*filleName = [NSStringstringWithFormat:@"%@%@",fillName,fillType];

    NSString*fillDocsPath = [savePathstringByAppendingPathComponent:filleName];

BOOLresult = [fileManagerfileExistsAtPath:fillDocsPath];

returnresult;

}

/*

 获取文件夹下所有文件的信息 fillPath文件夹路径 isascending是否升序 yes升序 no降序

 */

+ (NSMutableArray*)visitDirectoryList:(NSString*)fillPath Isascending:(BOOL)isascending{

NSArray*fileList  = [[NSFileManagerdefaultManager]subpathsAtPath:fillPath];// 取得目录下所有文件列表

fileList = [fileListsortedArrayUsingComparator:^(NSString*firFile,NSString*secFile) {// 将文件列表排序

NSString*firPath = [fillPathstringByAppendingPathComponent:firFile];// 获取前一个文件完整路径

NSString*secPath = [fillPathstringByAppendingPathComponent:secFile];// 获取后一个文件完整路径

NSDictionary*firFileInfo = [[NSFileManagerdefaultManager]attributesOfItemAtPath:firPatherror:nil];// 获取前一个文件信息

NSDictionary*secFileInfo = [[NSFileManagerdefaultManager]attributesOfItemAtPath:secPatherror:nil];// 获取后一个文件信息

idfirData = [firFileInfoobjectForKey:NSFileCreationDate];// 获取前一个文件创建时间

idsecData = [secFileInfoobjectForKey:NSFileCreationDate];// 获取后一个文件创建时间

if(isascending) {

return[firDatacompare:secData];// 升序

}else{

return[secDatacompare:firData];// 降序

        }

    }];

// 将所有文件按照日期分成数组

NSMutableArray  *listArray = [NSMutableArray new];//最终数组

NSMutableArray  *tempArray = [NSMutableArray new];//每天文件数组

    NSDateFormatter*format    = [[NSDateFormatter alloc] init];

    format.dateFormat=@"yyyy-MM-dd";

for(NSString*fileNameinfileList) {

        NSString*filePath = [fillPathstringByAppendingPathComponent:fileName];

NSDictionary*fileInfo = [[NSFileManagerdefaultManager]attributesOfItemAtPath:filePatherror:nil];// 获取文件信息

        NSMutableDictionary *fileDic = [NSMutableDictionary new];

fileDic[@"Name"] = fileName;//文件名字

fileDic[NSFileSize] = fileInfo[NSFileSize];//文件大小

fileDic[NSFileCreationDate] = fileInfo[NSFileCreationDate];//时间

if(tempArray.count > 0) {// 获取日期进行比较, 按照 XXXX 年 XX 月 XX 日来装数组

            NSString*currDate = [formatstringFromDate:fileInfo[NSFileCreationDate]];

            NSString*lastDate = [formatstringFromDate:tempArray.lastObject[NSFileCreationDate]];

if(![currDateisEqualToString:lastDate]) {

                [listArrayaddObject:tempArray];

                tempArray = [NSMutableArraynew];

            }

        }

        [tempArrayaddObject:fileDic];

    }

if(tempArray.count>0) {// 装载最后一个 array 数组

        listArray = tempArray;

    }

returnlistArray;

}

你可能感兴趣的:(转发一篇别人的方法文章)