Utils

//字典转json
+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
    
    NSError *parseError = nil;
    
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
//获取完整的文件路径
+ (NSString *)getFullFilePathInDocuments:(NSString *)subFilePath fileName:(NSString *)fileName {
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), subFilePath];
    //    NSLog(@"function:%s,getFilePath %@", __FUNCTION__,filePath);
    NSFileManager* fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:filePath]) {
        return [NSString stringWithFormat:@"%@/%@", filePath, fileName];
    }
    if ([fm createDirectoryAtPath:filePath
      withIntermediateDirectories:YES
                       attributes:nil
                            error:nil]) {
        u_int8_t b = 1;
        setxattr([filePath fileSystemRepresentation], "com.apple.MobileBackup", &b, 1, 0, 0);
        return [NSString stringWithFormat:@"%@/%@", filePath, fileName];
    }
    return nil;
}
//判断字符串是否都是空格
+ (BOOL)isEmpty:(NSString *)str {
    
    if (!str) {
        return YES;
    }else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet]; 
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return YES;
        }else {
            return NO;
        }
    }
}
//颜色转UIImage
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
//判断字符串是否含有EmoJi表情
+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                }else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                }else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    }else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    }else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    }else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    }else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
//本地文件转字典
+ (NSDictionary *)getDictFromFile:(NSString *)filePath {
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    if (dict == nil) {
        dict = [NSDictionary dictionary];
    }
    return dict;
}
//给空属性一个默认值 
+ (NSString *)nullToString:(id)value defaultValue:(NSString *)defaultValue {
    if (value == [NSNull null]) {
        return defaultValue;
    }
    if (value == nil) {
        return defaultValue;
    }
    if ([value isKindOfClass:[NSString class]]) {
        if ([value isEqualToString:@""]) {
            return defaultValue;
        }
    }
    return [NSString stringWithFormat:@"%@", value];
}

+ (NSNumber *)nullToNumber:(id)value defaultValue:(NSNumber *)defaultValue {
    if (value == [NSNull null]) {
        return defaultValue;
    }
    if (value == nil) {
        return defaultValue;
    }
    if (![value isKindOfClass:[NSNumber class]] && ![value isKindOfClass:[NSString class]]) {
        return defaultValue;
    }
    return value;
}

+ (NSDictionary *)nullToDict:(id)value defaultValue:(NSDictionary *)defaultValue {
    if (value == [NSNull null]) {
        return defaultValue;
    }
    if (value == nil) {
        return defaultValue;
    }
    if (![value isKindOfClass:[NSDictionary class]]) {
        return defaultValue;
    }
    return value;
}

+ (NSArray *)nullToArray:(id)value defaultValue:(NSArray *)defaultValue {
    if (value == [NSNull null]) {
        return defaultValue;
    }
    if (value == nil) {
        return defaultValue;
    }
    if (![value isKindOfClass:[NSArray class]]) {
        return defaultValue;
    }
    return value;
}
//匹配0-11个数字
+ (BOOL)validatePhoneNumbers:(NSString *)contents {
    NSString *regex = @"^[0-9]{0,11}$";
    NSPredicate *predictate = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",regex];
    if ([predictate evaluateWithObject:contents]) {
        return YES;
    }
    
    return NO;
}
//判断当前网络状态
#import "AFNetworkReachabilityManager.h"
+ (BOOL)isNetWorkReachable {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    NSInteger r = [manager networkReachabilityStatus];
    switch (r) {
        case AFNetworkReachabilityStatusUnknown:
            // 未知网络
            return YES;
            break;
        case AFNetworkReachabilityStatusNotReachable:
            // 没有网络连接
            return NO;
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            // 使用3G网络
            return YES;
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
            // 使用WiFi网络
            return YES;
            break;
    }
    return NO;
}
//返回当前时间Date类型
+ (NSDate *)getLocalCurrentDate {
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSDate *now = [NSDate date];
    NSInteger intervalNow = [zone secondsFromGMTForDate:now];
    NSDate *currentDate = [now dateByAddingTimeInterval:intervalNow];
    return currentDate;
}
//时间戳转字符串
+ (NSString *)getDate:(NSString *)date {
    long long time = [date longLongValue];
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//格式化
    [df setDateFormat:@"yyyy.MM.dd"];
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    NSString * timeStr = [df stringFromDate:d];
    return timeStr;
}
//根据时间字符串转日期
+ (NSDate *)getDateByTimestamp:(NSString *)DateStr {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [NSString stringWithFormat:@"%@ 00:00:00",DateStr];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSDate *)getDateByTimes:(NSString *)DateStr timeSting:(NSString *)str {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [NSString stringWithFormat:@"%@ %@",DateStr,str];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval: interval];
    return localeDate;
}
//添加晃动动画
+ (void)addShakeAnimationForView:(UIView *)view withDuration:(NSTimeInterval)duration {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
    CGFloat currentTx = view.transform.tx;
    animation.duration = duration;
    animation.values = @[ @(currentTx), @(currentTx - 15*kScaleX), @(currentTx), @(currentTx + 15*kScaleX), @(currentTx - 15*kScaleX), @(currentTx ), @(currentTx + 15*kScaleX), @(currentTx - 15*kScaleX), @(currentTx), @(currentTx + 15*kScaleX), @(currentTx )];
    animation.keyTimes = @[ @(0), @(0.1), @(0.2), @(0.3), @(0.4), @(0.5),  @(0.6), @(0.7), @(0.8),@(0.9),@(1) ];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [view.layer addAnimation:animation forKey:@"kViewShakerAnimationKey"];
}
//根据日期获取星期几
+ (NSString *)weekStringFromDate:(NSString *)dateStr {
    NSDate *date = [Utils getDateByTimestamp:dateStr];
    NSArray *weeks = @[[NSNull null],@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    NSString *identifier = nil;
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>8.0) {
        identifier = NSCalendarIdentifierGregorian;
    }else {
        identifier = NSCalendarIdentifierGregorian;
    }
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:identifier];
    NSTimeZone *timeZone = [[NSTimeZone alloc]initWithName:@"Asia/Beijing"];
    [calendar setTimeZone:timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *components = [calendar components:calendarUnit fromDate:date];
    return [weeks objectAtIndex:components.weekday];
}
//返回设备系统当前版本
[[[UIDevice currentDevice] systemVersion] doubleValue];
//获取手机型号
#import 
+ (NSString *)iphoneType {
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    
    if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    
    if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    
    if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    
    if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    
    if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
}
//判断机型
//判断是否是ipad
#define isPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
//判断iPhone4系列
#define kiPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPhone5系列
#define kiPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPhone6系列
#define kiPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iphone6+系列
#define kiPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPhoneX
#define IS_IPHONE_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPHoneXr
#define IS_IPHONE_Xr ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPhoneXs
#define IS_IPHONE_Xs ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
//判断iPhoneXs Max
#define IS_IPHONE_Xs_Max ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)

#define Height_StatusBar ((IS_IPHONE_X==YES || IS_IPHONE_Xr ==YES || IS_IPHONE_Xs== YES || IS_IPHONE_Xs_Max== YES) ? 44.0 : 20.0)
#define Height_NavBar ((IS_IPHONE_X==YES || IS_IPHONE_Xr ==YES || IS_IPHONE_Xs== YES || IS_IPHONE_Xs_Max== YES) ? 88.0 : 64.0)
#define Height_TabBar ((IS_IPHONE_X==YES || IS_IPHONE_Xr ==YES || IS_IPHONE_Xs== YES || IS_IPHONE_Xs_Max== YES) ? 83.0 : 49.0)
//App名称、版本
#define AppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#define AppName [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]

你可能感兴趣的:(Utils)