国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > iOS 常用公共方法

iOS 常用公共方法

来源:程序员人生   发布时间:2016-07-02 13:13:29 阅读次数:2535次

1、获得磁盘总空间大小

//磁盘总大小 + (CGFloat)diskofAllSizeMBytes{ CGFloat size = 0.0; NSError* error; NSDictionary* dic = [[NSFileManager defaultManager]attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error : %@",error.localizedDescription); #endif }else{ NSNumber* number = [dic objectForKey:NSFileSystemSize]; size = [number floatValue]/1024/1024; } return size; }

2、获得磁盘可用空间大小

//磁盘可用空间 + (CGFloat)diskofAllSizeMBytes{ CGFloat size = 0.0; NSError* error; NSDictionary* dic = [[NSFileManager defaultManager]attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error : %@",error.localizedDescription); #endif }else{ NSNumber* number = [dic objectForKey:NSFileSystemFreeSize]; size = [number floatValue]/1024/1024; } return size; }

3、获得指定路径下某个文件的大小

//获得文件大小 + (long long)fileSizeAtPath:(NSString *)filePath{ NSFileManager* fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:filePath]) { return 0; } return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; }

4、获得文件夹下所有文件的大小

//获得文件夹下所有文件的大小 + (long long)folderSizeAtPath:(NSString *)folderPath{ NSFileManager* fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:folderPath]) { return 0; } NSEnumerator* filesEnumerator = [[fileManager subpathsAtPath:folderPath]objectEnumerator]; NSString* fileName; long long folerSize = 0; while ((fileName = [filesEnumerator nextObject]) != nil) { NSString* filePath = [folderPath stringByAppendingPathComponent:fileName]; folerSize += [self fileSizeAtPath:filePath]; } return folerSize; } //获得文件大小 + (long long)fileSizeAtPath:(NSString *)filePath{ NSFileManager* fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:filePath]) { return 0; } return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; }

5、获得字符串(或汉字)首字母

//获得字符串(或汉字)首字母 + (NSString *)firstCharacterWithString:(NSString *)string{ NSMutableString* str = [NSMutableString stringWithString:string]; //汉字转英文 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString* pingyin = [str capitalizedString]; return [pingyin substringToIndex:1]; }

6、将字符串数组依照元素首字母顺序进行排序分组

//将字符串数组依照元素首字母顺序进行排序 + (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{ if (array.count == 0) { return nil; } for (id obj in array) { if (![obj isKindOfClass:[NSString class]]) { return nil; } } UILocalizedIndexedCollation* indexedCollation = [UILocalizedIndexedCollation currentCollation]; NSMutableArray* objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count]; //创建27个分组数组 for (int i = 0; i < indexedCollation.sectionTitles.count; i ++) { NSMutableArray* obj = [NSMutableArray array]; [objects addObject:obj]; } NSMutableArray* keys = [NSMutableArray arrayWithCapacity:objects.count]; //依照字母顺序进行分组 NSInteger lastIndex = -1; for (int i =0; i < array.count; i ++) { NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)]; [[objects objectAtIndex:index] addObject:array[i]]; lastIndex = index; } //去掉空数组 for (int i = 0; i < objects.count; i ++) { NSMutableArray* obj = objects[i]; if (obj.count == 0) { [objects removeObject:obj]; } } //获得索引字母 for (NSMutableArray* obj in objects) { NSString* str = obj[0]; NSString* key = [self firstCharacterWithString:str]; [keys addObject:key]; } NSMutableDictionary* dic = [NSMutableDictionary dictionary]; [dic setObject:objects forKey:keys]; return dic; } //获得字符串(或汉字)首字母 + (NSString *)firstCharacterWithString:(NSString *)string{ NSMutableString* str = [NSMutableString stringWithString:string]; //汉字转英文 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); NSString* pingyin = [str capitalizedString]; return [pingyin substringToIndex:1]; }

使用:

NSLog(@"%@",[[self class]dictionaryOrderByCharacterWithOriginalArray:@[@"guangzhou",@"shanghai",@"北京",@"henan"]]);

打印:

{ ( B, G, H, S ) = ( ( "\U5317\U4eac" ), ( guangzhou ), ( henan ), ( shanghai ) ); }

7、获得当前时间

//获得当前时间 //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]]; }

8、计算上第二天期距离现在多久,如XX小时前、XX分钟前等

/** * 计算上第二天期距离现在多久 * * @param lastTime 上第二天期(需要和格式对应) * @param format1 上第二天期格式 * @param currentTime 最近日期(需要和格式对应) * @param format2 最近日期格式 * * @return xx分钟前、xx小时前、xx天前 */ + (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lasetTimeFormat:(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 [self 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 mouth = intevalTime/60/60/24/30; NSInteger years = intevalTime/60/60/24/30/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 (mouth < 12){ NSDateFormatter* df = [[NSDateFormatter alloc]init]; df.dateFormat = @"M月d日"; NSString* time = [df stringFromDate:lastDate]; return time; }else if (years >= 1){ NSDateFormatter* df = [[NSDateFormatter alloc]init]; df.dateFormat = @"yyyy年M月d日"; NSString* time = [df stringFromDate:lastDate]; return time; } return @""; }

使用:

NSLog(@"%@",[[self class]timeIntervalFromLastTime:@"2016年6月27日 15:50" lasetTimeFormat:@"yyyy年MM月dd日 HH:mm" toCurrentTime:@"2016/6/27 16:12" currentTimeFormat:@"yyyy/MM/dd HH:mm"]);

打印:

22分钟前

9、判断手机号码格式是不是正确

//判断手机号码格式是不是正确 + (BOOL)valiMobile:(NSString *)mobile{ mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""]; if (mobile.length != 11) { return NO; } NSString *phoneRegex = @"^((17[0⑼])|(13[0⑼])|(15[^4,\\D])|(18[0,0⑼]))\\d{8}$"; NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex]; NSString *phoneRegex2=@"^1(47[0⑼])\\d{7}$"; NSPredicate *phoneTest2=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex2]; return [phoneTest evaluateWithObject:mobile]|[phoneTest2 evaluateWithObject:mobile]; }

10、判断邮箱格式是不是正确

//判断邮箱格式是不是正确 + (BOOL)isAvailableEmail:(NSString *)email{ NSString *emailRegex = @"[A-Z0⑼a-z._%+-]+@[A-Za-z0⑼.-]+\\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; return [emailTest evaluateWithObject:email]; }

11、对图片进行滤镜处理

#pragma mark -- 对图片进行滤镜处理 //name支持以下: //怀旧-->CIPhotoEffectInstant //单色-->CIPhotoEffectMono //黑白-->CIPhotoEffectNoir //退色-->CIPhotoEffectFade //色调-->CIPhotoEffectTonal //冲印-->CIPhotoEffectProcess //岁月-->CIPhotoEffectTransfer //铬黄-->CIPhotoEffectMono + (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; }

12、对图片进行模糊处理

//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) #pragma mark -- 对图片进行模糊处理 + (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; } }

13、调剂图片饱和度、亮度、对照度

/** * 调剂图片饱和度、亮度、对照度 * * @param image 目标图片 * @param saturation 饱和度 * @param brightness 亮度: ⑴.0~1.0 * @param contrast 对照度 * * @return 改变后图片 */ - (UIImage *)colorControlsWithOriginalImage:(UIImage *)image saturation:(CGFloat)saturation brightness:(CGFloat)brightness contrast:(CGFloat)contrast{ CIContext* context = [CIContext contextWithOptions:nil]; CIImage* inputImage = [[CIImage alloc]initWithImage:image]; CIFilter* filter = [CIFilter filterWithName:@"CIColorControls"]; [filter setValue:inputImage forKey:kCIInputImageKey]; [filter setValue:@(saturation) forKey:@"inputSaturation"]; [filter setValue:@(brightness) forKey:@"inputBrightness"]; [filter setValue:@(contrast) forKey:@"inputContrast"]; CIImage* result = [filter valueForKey:kCIOutputImageKey]; CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; UIImage* resultImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return resultImage; }

14、创建1张实时模糊效果的View(毛玻璃效果)

//Avilable in iOS 8.0 and later + (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{ UIBlurEffect* effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView* effectView = [[UIVisualEffectView alloc]initWithEffect:effect]; effectView.frame = frame; return effectView; }

15、全屏截图

//全屏截图 + (UIImage *)shotWithView:(UIView *)view{ UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }

16、全屏截图

//全屏截图 + (UIImage *)shotWithView:(UIView *)view{ UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }

17、截取view中某个区域生成1张图片

//截取view中某个区域生成1张图片 + (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{ CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope); UIGraphicsBeginImageContext(scope.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height); CGContextTranslateCTM(context, 0, rect.size.height);//下移 CGContextScaleCTM(context, 1.0f, -1.0f);//上翻 CGContextDrawImage(context, rect, imageRef); UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CGImageRelease(imageRef); CGContextRelease(context); return image; } //全屏截图 + (UIImage *)shotWithView:(UIView *)view{ UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }

18、紧缩图片到指定尺寸大小

//紧缩图片到指定尺寸大小 + (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{ UIImage* resultImage = image; UIGraphicsBeginImageContext(size); [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIGraphicsEndImageContext(); return resultImage; }

19、紧缩图片到指定文件大小

//紧缩图片到指定文件大小 + (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); CGFloat dataKBytes = data.length/1000.0; if (lastData == dataKBytes) { break; }else{ lastData = dataKBytes; } } return data; }

20、获得装备 IP 地址

需要先引入下头文件

#import <ifaddrs.h> #import <arpa/inet.h>
//获得装备IP地址 + (NSString *)getIPAddress{ NSString* address = @"error"; struct ifaddrs* interfaces = NULL; struct ifaddrs* temp_addr = NULL; int success = 0; success = getifaddrs(&interfaces); if (success == 0) { temp_addr = interfaces; while (temp_addr != NULL) { if (temp_addr->ifa_addr->sa_family == AF_INET) { if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } freeifaddrs(interfaces); return address; }

21、判断字符串中是不是含有空格

//判断字符串中是不是含有空格 + (BOOL)isHaceSpaceInString:(NSString *)string{ NSRange _range = [string rangeOfString:@" "]; if (_range.location != NSNotFound) { return YES; } return NO; }

22、判断字符串中是不是含有某个字符串

//判断字符串中是不是含有某个字符串 + (BOOL)isHaveString:(NSString *)string1 inString:(NSString *)string2{ NSRange _range = [string2 rangeOfString:string1]; if (_range.location != NSNotFound) { return YES; } return NO; }

23、判断字符串中是不是含有中文

//判断字符串中是不是含有中文 + (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; }

24、判断字符串是不是全部为数字

//判断字符串是不是全部为数字 + (BOOL)isAllNum:(NSString *)string{ unichar c; for (int i = 0; i < [string length]; i ++) { c = [string characterAtIndex:i]; if (!isdigit(c)) { return NO; } } return YES; }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生