2. 獲取磁碟可用空間大小 1 //磁碟可用空間 2 + (CGFloat)diskOfFreeSizeMBytes{ 3 CGFloat size = 0.0; 4 NSError *error; 5 NSDictionary *dic = [[NSFileManager defaultManag ...
1. 獲取磁碟總空間大小
1 //磁碟總空間 2 + (CGFloat)diskOfAllSizeMBytes{ 3 CGFloat size = 0.0; 4 NSError *error; 5 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; 6 if (error) { 7 #ifdef DEBUG 8 NSLog(@"error: %@", error.localizedDescription); 9 #endif 10 }else{ 11 NSNumber *number = [dic objectForKey:NSFileSystemSize]; 12 size = [number floatValue]/1024/1024; 13 } 14 return size; 15 }
2. 獲取磁碟可用空間大小
1 //磁碟可用空間 2 + (CGFloat)diskOfFreeSizeMBytes{ 3 CGFloat size = 0.0; 4 NSError *error; 5 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; 6 if (error) { 7 #ifdef DEBUG 8 NSLog(@"error: %@", error.localizedDescription); 9 #endif 10 }else{ 11 NSNumber *number = [dic objectForKey:NSFileSystemFreeSize]; 12 size = [number floatValue]/1024/1024; 13 } 14 return size; 15 }
3. 獲取指定路徑下某個文件的大小
1 //獲取文件大小 2 + (long long)fileSizeAtPath:(NSString *)filePath{ 3 NSFileManager *fileManager = [NSFileManager defaultManager]; 4 if (![fileManager fileExistsAtPath:filePath]) return 0; 5 return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; 6 }
4. 獲取文件夾下所有文件的大小
1 //獲取文件夾下所有文件的大小 2 + (long long)folderSizeAtPath:(NSString *)folderPath{ 3 NSFileManager *fileManager = [NSFileManager defaultManager]; 4 if (![fileManager fileExistsAtPath:folderPath]) return 0; 5 NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator]; 6 NSString *fileName; 7 long long folerSize = 0; 8 while ((fileName = [filesEnumerator nextObject]) != nil) { 9 NSString *filePath = [folderPath stringByAppendingPathComponent:fileName]; 10 folerSize += [self fileSizeAtPath:filePath]; 11 } 12 return folerSize; 13 }
5. 獲取字元串(或漢字)首字母
1 //獲取字元串(或漢字)首字母 2 + (NSString *)firstCharacterWithString:(NSString *)string{ 3 NSMutableString *str = [NSMutableString stringWithString:string]; 4 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); 5 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); 6 NSString *pingyin = [str capitalizedString]; 7 return [pingyin substringToIndex:1]; 8 }
6. 將字元串數組按照元素首字母順序進行排序分組
1 //將字元串數組按照元素首字母順序進行排序分組 2 + (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{ 3 if (array.count == 0) { 4 return nil; 5 } 6 for (id obj in array) { 7 if (![obj isKindOfClass:[NSString class]]) { 8 return nil; 9 } 10 } 11 UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation]; 12 NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count]; 13 //創建27個分組數組 14 for (int i = 0; i < indexedCollation.sectionTitles.count; i++) { 15 NSMutableArray *obj = [NSMutableArray array]; 16 [objects addObject:obj]; 17 } 18 NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count]; 19 //按字母順序進行分組 20 NSInteger lastIndex = -1; 21 for (int i = 0; i < array.count; i++) { 22 NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)]; 23 [[objects objectAtIndex:index] addObject:array[i]]; 24 lastIndex = index; 25 } 26 //去掉空數組 27 for (int i = 0; i < objects.count; i++) { 28 NSMutableArray *obj = objects[i]; 29 if (obj.count == 0) { 30 [objects removeObject:obj]; 31 } 32 } 33 //獲取索引字母 34 for (NSMutableArray *obj in objects) { 35 NSString *str = obj[0]; 36 NSString *key = [self firstCharacterWithString:str]; 37 [keys addObject:key]; 38 } 39 NSMutableDictionary *dic = [NSMutableDictionary dictionary]; 40 [dic setObject:objects forKey:keys]; 41 return dic; 42 } 43 44 //獲取字元串(或漢字)首字母 45 + (NSString *)firstCharacterWithString:(NSString *)string{ 46 NSMutableString *str = [NSMutableString stringWithString:string]; 47 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); 48 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); 49 NSString *pingyin = [str capitalizedString]; 50 return [pingyin substringToIndex:1]; 51 }
使用如下:
NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];
NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];
NSLog(@"\n\ndic: %@", dic);
輸出結果如下:
輸出結果
7. 獲取當前時間
1 //獲取當前時間 2 //format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH時mm分ss秒" 3 + (NSString *)currentDateWithFormat:(NSString *)format{ 4 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 5 [dateFormatter setDateFormat:format]; 6 return [dateFormatter stringFromDate:[NSDate date]]; 7 }
8. 計算上次日期距離現在多久, 如 xx 小時前、xx 分鐘前等
1 /** 2 * 計算上次日期距離現在多久 3 * 4 * @param lastTime 上次日期(需要和格式對應) 5 * @param format1 上次日期格式 6 * @param currentTime 最近日期(需要和格式對應) 7 * @param format2 最近日期格式 8 * 9 * @return xx分鐘前、xx小時前、xx天前 10 */ 11 + (NSString *)timeIntervalFromLastTime:(NSString *)lastTime 12 lastTimeFormat:(NSString *)format1 13 ToCurrentTime:(NSString *)currentTime 14 currentTimeFormat:(NSString *)format2{ 15 //上次時間 16 NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init]; 17 dateFormatter1.dateFormat = format1; 18 NSDate *lastDate = [dateFormatter1 dateFromString:lastTime]; 19 //當前時間 20 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init]; 21 dateFormatter2.dateFormat = format2; 22 NSDate *currentDate = [dateFormatter2 dateFromString:currentTime]; 23 return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate]; 24 } 25 26 + (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{ 27 NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; 28 //上次時間 29 NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]]; 30 //當前時間 31 NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]]; 32 //時間間隔 33 NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate]; 34 35 //秒、分、小時、天、月、年 36 NSInteger minutes = intevalTime / 60; 37 NSInteger hours = intevalTime / 60 / 60; 38 NSInteger day = intevalTime / 60 / 60 / 24; 39 NSInteger month = intevalTime / 60 / 60 / 24 / 30; 40 NSInteger yers = intevalTime / 60 / 60 / 24 / 365; 41 42 if (minutes <= 10) { 43 return @"剛剛"; 44 }else if (minutes < 60){ 45 return [NSString stringWithFormat: @"%ld分鐘前",(long)minutes]; 46 }else if (hours < 24){ 47 return [NSString stringWithFormat: @"%ld小時前",(long)hours]; 48 }else if (day < 30){ 49 return [NSString stringWithFormat: @"%ld天前",(long)day]; 50 }else if (month < 12){ 51 NSDateFormatter * df =[[NSDateFormatter alloc]init]; 52 df.dateFormat = @"M月d日"; 53 NSString * time = [df stringFromDate:lastDate]; 54 return time; 55 }else if (yers >= 1){ 56 NSDateFormatter * df =[[NSDateFormatter alloc]init]; 57 df.dateFormat = @"yyyy年M月d日"; 58 NSString * time = [df stringFromDate:lastDate]; 59 return time; 60 } 61 return @""; 62 }
使用如下:
NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50"
lastTimeFormat:@"yyyy年MM月dd日 HH:mm"
ToCurrentTime:@"2015/12/08 16:12"
currentTimeFormat:@"yyyy/MM/dd HH:mm"]);
輸出結果如下:
輸出結果
9. 判斷手機號碼格式是否正確
1 //判斷手機號碼格式是否正確 2 + (BOOL)valiMobile:(NSString *)mobile{ 3 mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""]; 4 if (mobile.length != 11) 5 { 6 return NO; 7 }else{ 8 /** 9 * 移動號段正則表達式 10 */ 11 NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"; 12 /** 13 * 聯通號段正則表達式 14 */ 15 NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"; 16 /** 17 * 電信號段正則表達式 18 */ 19 NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$"; 20 NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM]; 21 BOOL isMatch1 = [pred1 evaluateWithObject:mobile]; 22 NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM]; 23 BOOL isMatch2 = [pred2 evaluateWithObject:mobile]; 24 NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM]; 25 BOOL isMatch3 = [pred3 evaluateWithObject:mobile]; 26 27 if (isMatch1 || isMatch2 || isMatch3) { 28 return YES; 29 }else{ 30 return NO; 31 } 32 } 33 }
10. 判斷郵箱格式是否正確
1 //利用正則表達式驗證 2 + (BOOL)isAvailableEmail:(NSString *)email { 3 NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 4 NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 5 return [emailTest evaluateWithObject:email]; 6 }
11. 將十六進位顏色轉換為 UIColor 對象
1 //將十六進位顏色轉換為 UIColor 對象 2 + (UIColor *)colorWithHexString:(NSString *)color{ 3 NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; 4 // String should be 6 or 8 characters 5 if ([cString length] < 6) { 6 return [UIColor clearColor]; 7 } 8 // strip "0X" or "#" if it appears 9 if ([cString hasPrefix:@"0X"]) 10 cString = [cString substringFromIndex:2]; 11 if ([cString hasPrefix:@"#"]) 12 cString = [cString substringFromIndex:1]; 13 if ([cString length] != 6) 14 return [UIColor clearColor]; 15 // Separate into r, g, b substrings 16 NSRange range; 17 range.location = 0; 18 range.length = 2; 19 //r 20 NSString *rString = [cString substringWithRange:range]; 21 //g 22 range.location = 2; 23 NSString *gString = [cString substringWithRange:range]; 24 //b 25 range.location = 4; 26 NSString *bString = [cString substringWithRange:range]; 27 // Scan values 28 unsigned int r, g, b; 29 [[NSScanner scannerWithString:rString] scanHexInt:&r]; 30 [[NSScanner scannerWithString:gString] scanHexInt:&g]; 31 [[NSScanner scannerWithString:bString] scanHexInt:&b]; 32 return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; 33 }
12. 對圖片進行濾鏡處理
1 #pragma mark - 對圖片進行濾鏡處理 2 // 懷舊 --> CIPhotoEffectInstant 單色 --> CIPhotoEffectMono 3 // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade 4 // 色調 --> CIPhotoEffectTonal 沖印 --> CIPhotoEffectProcess 5 // 歲月 --> CIPhotoEffectTransfer 鉻黃 --> CIPhotoEffectChrome 6 // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField 7 + (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{ 8 CIContext *context = [CIContext contextWithOptions:nil]; 9 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 10 CIFilter *filter = [CIFilter filterWithName:name]; 11 [filter setValue:inputImage forKey:kCIInputImageKey]; 12 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 13 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 14 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 15 CGImageRelease(cgImage); 16 return resultImage; 17 }
13. 對圖片進行模糊處理
1 #pragma mark - 對圖片進行模糊處理 2 // CIGaussianBlur ---> 高斯模糊 3 // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later) 4 // CIDiscBlur ---> 環形捲積模糊(Available in iOS 9.0 and later) 5 // CIMedianFilter ---> 中值模糊, 用於消除圖像噪點, 無需設置radius(Available in iOS 9.0 and later) 6 // CIMotionBlur ---> 運動模糊, 用於模擬相機移動拍攝時的掃尾效果(Available in iOS 9.0 and later) 7 + (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{ 8 CIContext *context = [CIContext contextWithOptions:nil]; 9 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 10 CIFilter *filter; 11 if (name.length != 0) { 12 filter = [CIFilter filterWithName:name]; 13 [filter setValue:inputImage forKey:kCIInputImageKey]; 14 if (![name isEqualToString:@"CIMedianFilter"]) { 15 [filter setValue:@(radius) forKey:@"inputRadius"]; 16 } 17 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 18 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 19 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 20 CGImageRelease(cgImage); 21 return resultImage; 22 }else{ 23 return nil; 24 } 25 }
14. 調整圖片飽和度、亮度、對比度
1 /** 2 * 調整圖片飽和度, 亮度, 對比度 3 * 4 * @param image 目標圖片 5 * @param saturation 飽和度 6 * @param brightness 亮度: -1.0 ~ 1.0 7 * @param contrast 對比度 8 * 9 */ 10 + (UIImage *)colorControlsWithOriginalImage:(UIImage *)image 11 saturation:(CGFloat)saturation 12 brightness:(CGFloat)brightness 13 contrast:(CGFloat)contrast{ 14 CIContext *context = [CIContext contextWithOptions:nil]; 15 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 16 CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"]; 17 [filter setValue:inputImage forKey:kCIInputImageKey]; 18 19 [filter setValue:@(saturation) forKey:@"inputSaturation"]; 20 [filter setValue:@(brightness) forKey:@"inputBrightness"]; 21 [filter setValue:@(contrast) forKey:@"inputContrast"]; 22 23 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 24 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 25 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 26 CGImageRelease(cgImage); 27 return resultImage; 28 }
15. 創建一張實時模糊效果 View (毛玻璃效果)
1 //Avilable in iOS 8.0 and later 2 + (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{ 3 UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; 4 UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; 5 effectView.frame = frame; 6 return effectView; 7 }
16. 全屏截圖
1 //全屏截圖 2 + (UIImage *)shotScreen{ 3 UIWindow *window = [UIApplication sharedApplication].keyWindow; 4 UIGraphicsBeginImageContext(window.bounds.size); 5 [window.layer renderInContext:UIGraphicsGetCurrentContext()]; 6 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 7 UIGraphicsEndImageContext(); 8 return image; 9 }
17. 截取一張 view 生成圖片
1 //截取view生成一張圖片 2 + (UIImage *)shotWithView:(UIView *)view{ 3 UIGraphicsBeginImageContext(view.bounds.size); 4 [view.layer renderInContext:UIGraphicsGetCurrentContext()]; 5 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 6 UIGraphicsEndImageContext(); 7 return image; 8 }
18. 截取view中某個區域生成一張圖片
1 //截取view中某個區域生成一張圖片 2 + (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{ 3 CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope); 4 UIGraphicsBeginImageContext(scope.size); 5 CGContextRef context = UIGraphicsGetCurrentContext(); 6 CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height); 7 CGContextTranslateCTM(context, 0, rect.size.height);//下移 8 CGContextScaleCTM(context, 1.0f, -1.0f);//上翻 9 CGContextDrawImage(context, rect, imageRef); 10 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 11 UIGraphicsEndImageContext(); 12 CGImageRelease(imageRef); 13 CGContextRelease(context); 14 return image; 15 }
19. 壓縮圖片到指定尺寸大小
1 //壓縮圖片到指定尺寸大小 2 + (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{ 3 UIImage *resultImage = image; 4 UIGraphicsBeginImageContext(size); 5 [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; 6 UIGraphicsEndImageContext(); 7 return resultImage; 8 }
20. 壓縮圖片到指定文件大小
1 //壓縮圖片到指定文件大小 2 + (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{ 3 NSData *data = UIImageJPEGRepresentation(image, 1.0); 4 CGFloat dataKBytes = data.length/1000.0; 5 CGFloat maxQuality = 0.9f; 6 CGFloat lastData = dataKBytes; 7 while (dataKBytes > size && maxQuality > 0.01f) { 8 maxQuality = maxQuality - 0.01f; 9 data = UIImageJPEGRepresentation(image, maxQuality); 10 dataKBytes = data.length/1000.0; 11 if (lastData == dataKBytes) { 12 break; 13 }else{ 14 lastData = dataKBytes; 15 } 16 } 17 return data; 18 }
21. 獲取設備 IP 地址
1 需要先引入下頭文件: 2 3 #import <ifaddrs.h> 4 #import <arpa/inet.h> 5 代碼: 6 7 //獲取設備 IP 地址 8 + (NSString *)getIPAddress { 9 NSString *address = @"error"; 10 struct ifaddrs *interfaces = NULL; 11 struct ifaddrs *temp_addr = NULL; 12 int success = 0; 13 success = getifaddrs(&interfaces); 14 if (success == 0) { 15 temp_addr = interfaces; 16 while(temp_addr != NULL) { 17 if(temp_addr->ifa_addr->sa_family == AF_INET) { 18 if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { 19 address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; 20 } 21 } 22 temp_addr = temp_addr->ifa_next; 23 } 24 } 25 freeifaddrs(interfaces); 26 return address; 27 }
22. 判斷字元串中是否含有空格
1 + (BOOL)isHaveSpaceInString:(NSString *)string{ 2 NSRange _range = [string rangeOfString:@" "]; 3 if (_range.location != NSNotFound) { 4 return YES; 5 }else { 6 return NO; 7 } 8 }
23. 判斷字元串中是否含有某個字元串
1 + (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{ 2 NSRange _range = [string2 rangeOfString:string1]; 3 if (_range.location != NSNotFound) { 4 return YES; 5 }else { 6 return NO; 7 } 8 }
24. 判斷字元串中是否含有中文
1 + (BOOL)isHaveChineseInString:(NSString *)string{ 2 for(NSInteger i = 0; i < [string length]; i++){ 3 int a = [string characterAtIndex:i]