iOS 常用方法封装 分享一下

iOS 常用方法封装  分享一下   欢迎补充

.h方法

+ (NSString *)md5big:(NSString*)input;

+ (NSString *)md5small:(NSString*)input;

//检测网络

+ (BOOL)checkNetWorkAvailable;

//网络失败样式

+ (void)asiRequestFail:(UIView *)view;

//获取本地版本号

+(NSString*) getLocalAppVersion;

//获取BundleID

+(NSString*) getBundleID;

//获取app的名字

+(NSString*) getAppName;

//16进制颜色改为UIcolor

+(UIColor *)getColor:(NSString *) hexColor;

/*手机号码验证 MODIFIED BY HELENSONG*/

+(BOOL) isValidateMobile:(NSString *)mobile;

//判断字符串是否为空

+(BOOL) isBlankString:(NSString *)string;

//字典转json

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

//生成guid

+ (NSString *)getUniqueStrByUUID;

//反序列化

+(NSDictionary *)jsonDictionarBystring:(NSString *)message;

//压缩图片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size;

//压缩图片到指定文件大小

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size;

//判断是否有空格

+ (BOOL)isHaveSpaceInString:(NSString *)string;

//判断是否有中文

+ (BOOL)isHaveChineseInString:(NSString *)string;

//获取当前的viewcontroller

+ (UIViewController *)getCurrentVC;

//对图片进行模糊处理

+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius;

//对图片进行滤镜处理

+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name;

//获取当前时间

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"

+ (NSString *)currentDateWithFormat:(NSString *)format;

//计算上次日期距离现在多久

+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime

lastTimeFormat:(NSString *)format1

ToCurrentTime:(NSString *)currentTime

currentTimeFormat:(NSString *)format2;

//获取文件大小

+ (long long)fileSizeAtPath:(NSString *)filePath;

//根据日期算出周几

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate;


.m实现

//MD5 小写加密

+ (NSString *)md5big:(NSString*)input

{

const char *cStr = [input UTF8String];

unsigned char result[16];

CC_MD5(cStr, (CC_LONG)strlen(cStr), result);

return [NSString stringWithFormat:

@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",

result[0], result[1], result[2], result[3],

result[4], result[5], result[6], result[7],

result[8], result[9], result[10], result[11],

result[12], result[13], result[14], result[15]

];

}



// MD5 大写加密

+ (NSString *)md5small:(NSString*)input

{

const char *cStr = [input UTF8String];

unsigned char result[16];

CC_MD5(cStr, (CC_LONG)strlen(cStr), result);

return [NSString stringWithFormat:

@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",

result[0], result[1], result[2], result[3],

result[4], result[5], result[6], result[7],

result[8], result[9], result[10], result[11],

result[12], result[13], result[14], result[15]

];

}

//网络异常情况样式

+ (void)asiRequestFail:(UIView *)view

{

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];

hud.labelText = @"网络异常, 请重试";

//设置样式

hud.mode = MBProgressHUDModeText;

hud.removeFromSuperViewOnHide = YES;

[hud hide:YES afterDelay:1];

}

+(BOOL)checkNetWorkAvailable{

BOOL result = [self isNetWorkAvailable];

if(!result){

[MBProgressHUD showError:@"当前网络不佳,请检查网络" toView:nil];

}

return result;

}

+(BOOL)isNetWorkAvailable{

return [self isWIFIAvailable] || [self is3GAvailable];

}

// 是否wifi

+ (BOOL) isWIFIAvailable {

return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

}

// 是否3G

+ (BOOL) is3GAvailable {

return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

}

//获取本地版本号

+(NSString*) getLocalAppVersion

{

return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

}

//获取BundleID

+(NSString*) getBundleID

{

return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];

}

//获取app的名字

+(NSString*) getAppName

{

return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];

}

//16进制颜色改为UIcolor

+(UIColor *)getColor:(NSString *) hexColor{

unsigned int red,green,blue;

NSRange range;

range.length = 2;

range.location = 0;

[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];

range.location = 2;

[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];

range.location = 4;

[[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];

return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green / 255.0f) blue:(float)(blue / 255.0f)alpha:1.0f];

}

/*手机号码验证 MODIFIED BY HELENSONG*/

+(BOOL) isValidateMobile:(NSString *)mobile

{

//手机号以1开头,9个 \d 数字字符^1[3|4|5|8] \d{9}$

NSString *phoneRegex = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";

NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];

return [phoneTest evaluateWithObject:mobile];

}

//判断字符串是否为空

+ (BOOL) isBlankString:(NSString *)string {

if (string == nil || string == NULL) {

return YES;

}

if ([string isKindOfClass:[NSNull class]]) {

return YES;

}

if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {

return YES;

}

return NO;

}

//字典转json

+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{

NSError *parseError = nil;

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

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

}

//生成uuid

+ (NSString *)getUniqueStrByUUID

{

CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID

//get the string representation of the UUID

NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);

CFRelease(uuidObj);

return uuidString;

}

//反序列化

+(NSDictionary *)jsonDictionarBystring:(NSString *)message{

NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];

NSError *err;

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingMutableContainers

error:&err];;

return dic;

}

//压缩图片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{

UIImage *resultImage = image;

UIGraphicsBeginImageContext(size);

[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

UIGraphicsEndImageContext();

return resultImage;

}

//压缩图片到指定文件大小

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{

NSData *data = UIImageJPEGRepresentation(image, 1.0);

CGFloat dataKBytes = data.length/1000.0;

CGFloat maxQuality = 0.9f;

CGFloat lastData = dataKBytes;

while (dataKBytes > size && maxQuality > 0.01f) {

maxQuality = maxQuality - 0.01f;

data = UIImageJPEGRepresentation(image, maxQuality);

dataKBytes = data.length/1000.0;

if (lastData == dataKBytes) {

break;

}else{

lastData = dataKBytes;

}

}

return data;

}

//判断是否有空格

+ (BOOL)isHaveSpaceInString:(NSString *)string{

NSRange _range = [string rangeOfString:@" "];

if (_range.location != NSNotFound) {

return YES;

}else {

return NO;

}

}

//判断是否有中文

+ (BOOL)isHaveChineseInString:(NSString *)string{

for(NSInteger i = 0; i < [string length]; i++){

int a = [string characterAtIndex:i];

if (a > 0x4e00 && a < 0x9fff) {

return YES;

}

}

return NO;

}

//获取当前的viewcontroller

+ (UIViewController *)getCurrentVC

{

UIViewController *result = nil;

UIWindow * window = [[UIApplication sharedApplication] keyWindow];

if (window.windowLevel != UIWindowLevelNormal)

{

NSArray *windows = [[UIApplication sharedApplication] windows];

for(UIWindow * tmpWin in windows)

{

if (tmpWin.windowLevel == UIWindowLevelNormal)

{

window = tmpWin;

break;

}

}

}

UIView *frontView = [[window subviews] objectAtIndex:0];

id nextResponder = [frontView nextResponder];

if ([nextResponder isKindOfClass:[UIViewController class]])

result = nextResponder;

else

result = window.rootViewController;

return result;

}

#pragma mark - 对图片进行模糊处理

// CIGaussianBlur ---> 高斯模糊

// CIBoxBlur      ---> 均值模糊(Available in iOS 9.0 and later)

// CIDiscBlur     ---> 环形卷积模糊(Available in iOS 9.0 and later)

// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)

// CIMotionBlur   ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)

+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{

CIContext *context = [CIContext contextWithOptions:nil];

CIImage *inputImage = [[CIImage alloc] initWithImage:image];

CIFilter *filter;

if (name.length != 0) {

filter = [CIFilter filterWithName:name];

[filter setValue:inputImage forKey:kCIInputImageKey];

if (![name isEqualToString:@"CIMedianFilter"]) {

[filter setValue:@(radius) forKey:@"inputRadius"];

}

CIImage *result = [filter valueForKey:kCIOutputImageKey];

CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

CGImageRelease(cgImage);

return resultImage;

}else{

return nil;

}

}

#pragma mark - 对图片进行滤镜处理

// 怀旧 --> CIPhotoEffectInstant                         单色 --> CIPhotoEffectMono

// 黑白 --> CIPhotoEffectNoir                            褪色 --> CIPhotoEffectFade

// 色调 --> CIPhotoEffectTonal                           冲印 --> CIPhotoEffectProcess

// 岁月 --> CIPhotoEffectTransfer                        铬黄 --> CIPhotoEffectChrome

// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField

+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{

CIContext *context = [CIContext contextWithOptions:nil];

CIImage *inputImage = [[CIImage alloc] initWithImage:image];

CIFilter *filter = [CIFilter filterWithName:name];

[filter setValue:inputImage forKey:kCIInputImageKey];

CIImage *result = [filter valueForKey:kCIOutputImageKey];

CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

CGImageRelease(cgImage);

return resultImage;

}

//获取当前时间

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"

+ (NSString *)currentDateWithFormat:(NSString *)format{

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

[dateFormatter setDateFormat:format];

return [dateFormatter stringFromDate:[NSDate date]];

}

/**

*  计算上次日期距离现在多久

*

*  @param lastTime    上次日期(需要和格式对应)

*  @param format1     上次日期格式

*  @param currentTime 最近日期(需要和格式对应)

*  @param format2     最近日期格式

*

*  @return xx分钟前、xx小时前、xx天前

*/

+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime

lastTimeFormat:(NSString *)format1

ToCurrentTime:(NSString *)currentTime

currentTimeFormat:(NSString *)format2{

//上次时间

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

dateFormatter1.dateFormat = format1;

NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];

//当前时间

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

dateFormatter2.dateFormat = format2;

NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];

return [Utility timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];

}

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{

NSTimeZone *timeZone = [NSTimeZone systemTimeZone];

//上次时间

NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];

//当前时间

NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];

//时间间隔

NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

//秒、分、小时、天、月、年

NSInteger minutes = intevalTime / 60;

NSInteger hours = intevalTime / 60 / 60;

NSInteger day = intevalTime / 60 / 60 / 24;

NSInteger month = intevalTime / 60 / 60 / 24 / 30;

NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

if (minutes <= 10) {

return  @"刚刚";

}else if (minutes < 60){

return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];

}else if (hours < 24){

return [NSString stringWithFormat: @"%ld小时前",(long)hours];

}else if (day < 30){

return [NSString stringWithFormat: @"%ld天前",(long)day];

}else if (month < 12){

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

df.dateFormat = @"M月d日";

NSString * time = [df stringFromDate:lastDate];

return time;

}else if (yers >= 1){

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

df.dateFormat = @"yyyy年M月d日";

NSString * time = [df stringFromDate:lastDate];

return time;

}

return @"";

}

//获取文件大小

+ (long long)fileSizeAtPath:(NSString *)filePath{

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:filePath]) return 0;

return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];

}

//根据日期算出周几

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate

{

NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

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

NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

[calendar setTimeZone: timeZone];

NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

return [weekdays objectAtIndex:theComponents.weekday];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容