常用iOS-oc工具方法总结

//
//  AICommonHelper.m
//  TJCMClient
//
//  Created by 赵梁 on 16/6/30.
//  Copyright © 2016年 asiainfo. All rights reserved.
//

#import "AICommonHelper.h"

#import <ifaddrs.h>
#import <arpa/inet.h>

@implementation AICommonHelper

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

//2. 获取磁盘可用空间大小
+ (CGFloat)diskOfFreeSizeMBytes
{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {
        NSLog(@"error: %@", error.localizedDescription);
    }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 *flieName;
    long long folderSize = 0;
    while ((flieName = [filesEnumerator nextObject]) != nil) {
        NSString *filePath = [folderPath stringByAppendingPathComponent:flieName];
        folderSize += [self fileSizeAtPath:filePath];
    }
    return folderSize;
}

//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 substringFromIndex: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 (NSInteger i = 0; i < indexedCollation.sectionTitles.count; i++) {
        NSMutableArray *obj = [NSMutableArray array];
        [objects addObject:obj];
    }

    //按字符顺序进行分组
    NSInteger lastIndex = -1;

    for (id obj in array) {
        NSInteger index = [indexedCollation sectionForObject:obj collationStringSelector:@selector(uppercaseString)];
        [[objects objectAtIndex:index] addObject:obj];
        lastIndex = index;
    }

    //去掉空数组
    for (NSMutableArray *obj in objects) {
        if (obj.count==0) {
            [objects removeObject:obj];
        }
    }

    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
    //获取索引字母
    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;
    //使用如下:
//    NSArray *arr = @[@"guangzhou",@"shanghai",@"北京",@"天津",@"河南"];
//    NSDictionary *dic = [self dictionaryOrderByCharacterWithOriginalArray:arr];
//    NSLog(@"\n\ndic:%@",dic);
}

//7. 获取当前时间
//format:@"yyyy-MM-dd HH:mm:ss" @"yyyy年MM月dd日 HH时mm分ss秒"
+ (NSString *)currentDateWithFormat:(NSString *)format
{
    return [self stringFromDate:[NSDate date] withFormat:format];
}

+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:date];
}

+ (NSDate *)dateFromString:(NSString *)dateString withFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter dateFromString:dateString];
}

//8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等
+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormate:(NSString *)lastTimeFormate
                         toCurrentTime:(NSString *)currentTime currentTimeFormate:(NSString *)currentTimeFormate
{
    NSDate *lastDate = [self dateFromString:lastTime withFormat:lastTimeFormate];
    NSDate *currentDate = [self dateFromString:currentTime withFormat:currentTimeFormate];
    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 month = intevalTime/60/60/24/30;
    NSInteger year = 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)minutes];
    }else if (day < 30){
        return [NSString stringWithFormat:@"%ld天前",(long)minutes];
    }else if (month < 12){
        return [self stringFromDate:lastDate withFormat:@"M月d日"];
    }else if (year>=1){
        return [self stringFromDate:lastDate withFormat:@"yyyy年M月d日"];
    }
    return @"";
}

//9. 判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11) {
        return NO;
    }else {
        //移动号段正则表达式
        NSString *CM_NUM = @"^((13[4-9])|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";

        //联通号段正则表达式
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";

        //移动号段正则表达式
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";

        NSPredicate *pred_CM_NUM = [NSPredicate predicateWithFormat:@"SELF MATCH %@",CM_NUM];
        BOOL isMatch_CM_NUM = [pred_CM_NUM evaluateWithObject:mobile];
        NSPredicate *pred_CU_NUM = [NSPredicate predicateWithFormat:@"SELF MATCH %@",CU_NUM];
        BOOL isMatch_CU_NUM = [pred_CU_NUM evaluateWithObject:mobile];
        NSPredicate *pred_CT_NUM = [NSPredicate predicateWithFormat:@"SELF MATCH %@",CT_NUM];
        BOOL isMatch_CT_NUM = [pred_CT_NUM evaluateWithObject:mobile];
        if (isMatch_CM_NUM||isMatch_CT_NUM||isMatch_CU_NUM) {
            return YES;
        }else {
            return NO;
        }
    }
}

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

//11. 将十六进制颜色转换为 UIColor 对象

/*!
 *  @author 赵梁, 16-07-01 00:07:18
 *
 *  @brief 12. 对图片进行滤镜处理
 *
 *  @param image 图片
 *  @param name  滤镜
 *  CIPhotoEffectInstant 
 [84] = "CIPhotoEffectChrome"
 [85] = "CIPhotoEffectFade"
 [86] = "CIPhotoEffectInstant"
 [87] = "CIPhotoEffectMono"
 [88] = "CIPhotoEffectNoir"
 [89] = "CIPhotoEffectProcess"
 [90] = "CIPhotoEffectTonal"
 [91] = "CIPhotoEffectTransfer"
 *  @return <#return value description#>
 *
 *  @since 2.0.0
 */
+ (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;
}

/*!
 *  @author 赵梁, 16-07-01 00:07:02
 *
 *  @brief 13. 对图片进行模糊处理
 *
 *  @param image  原生图片
 *  @param name   模糊处理
 *  @param radius 模糊半径
 *
 *  @return 图片
 *
 *  @since 2.0.0
 */
+ (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;
    }
}

/*!
 *  @author 赵梁, 16-07-01 01:07:22
 *
 *  @brief 14. 调整图片饱和度、亮度、对比度
 *
 *  @param image      目标图片
 *  @param saturation 饱和度
 *  @param brightness 亮度 -1.0 ~ 1.0
 *  @param contrast   对比度
 *
 *  @return <#return value description#>
 *
 *  @since 2.0.0
 */
+ (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;
}

/*!
 *  @author 赵梁, 16-07-01 01:07:19
 *
 *  @brief //15. 创建一张实时模糊效果 View (毛玻璃效果)
 *  ios 8.0 以后可用
 *  @param frame <#frame description#>
 *
 *  @return <#return value description#>
 *
 *  @since 2.0.0
 */
+ (UIVisualEffectView *)effectViewWitFrame:(CGRect)frame
{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = frame;
    return effectView;
}

//16. 全屏截图
+ (UIImage *)shotScreen
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIGraphicsBeginImageContext(window.bounds.size);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//17. 截取一张 view 生成图片
+ (UIImage *)shotWithView:(UIView*)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//18. 截取view中某个区域生成一张图片
+ (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, -1);//上翻
    CGContextDrawImage(context, rect, imageRef);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    CGImageRelease(imageRef);
    CGContextRelease(context);

    return image;
}

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

    return resultImage;
}

//20. 压缩图片到指定文件大小
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size
{
    NSData *data = UIImageJPEGRepresentation(image, 1);
    CGFloat dataKBytes = data.length/1000.0f;
    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;
}


//21. 获取设备 IP 地址
+ (NSString *)getIPAddress
{
    NSString *address = @"Error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);

    return address;
}

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

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

//24. 判断字符串中是否含有中文
+ (BOOL)isHaveChineseString:(NSString *)string
{
    for (NSInteger i=0; i<string.length; i++) {
        int a = [string characterAtIndex:i];
        if (a > 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

//25. 判断字符串是否全部为数字
+ (BOOL)isAllNum:(NSString *)string
{
    unichar c;
    for (NSInteger i=0; i<string.length; i++) {
        c = [string characterAtIndex:i];
        if (!isdigit(c)) {
            return NO;
        }
    }
    return YES;
}

//26. 绘制虚线
+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame lineLeght:(int)lenght lineSpacing:(int)spacing lineColor:(UIColor *)color
{
    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];
    dashedLine.backgroundColor = [UIColor clearColor];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.bounds = dashedLine.bounds;
    shapeLayer.position = CGPointMake(CGRectGetWidth(dashedLine.frame)/2, CGRectGetHeight(dashedLine.frame));
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = color.CGColor;
    shapeLayer.lineWidth = CGRectGetHeight(dashedLine.frame);
    shapeLayer.lineJoin = kCALineJoinRound;
    shapeLayer.lineDashPattern = @[[NSNumber numberWithInt:lenght],[NSNumber numberWithInt:spacing]];

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);
    shapeLayer.path = path;
    CGPathRelease(path);
    [dashedLine.layer addSublayer:shapeLayer];

    return dashedLine;
}



@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值