总结iOS开发中常用的辅助方法

1.Keychain本地长期键值存储

//删除
+(void)deleteStringForKey:(NSString *)aKey 
{
    NSMutableDictionary *query = [NSMutableDictionary dictionary];
    [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge  id)kSecClass];
    [query setObject:(id)aKey forKey:(__bridge id)kSecAttrAccount];
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    if (status != noErr) {
    // NSLog(@"[KeychainAccessor]>>> SecItemDelete result in error:(%d)", (int)status);
    }
}
//存储
+ (void)setString:(NSString *)aString forKey:(NSString *)aKey 
{
    NSData *savingData = [aString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    [attributes setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [attributes setObject:(id)aKey forKey:(__bridge id)kSecAttrAccount];
    [attributes setObject:savingData forKey:(__bridge id)kSecValueData];
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);
    if ((int)status==-25299) {
        //  NSLog(@"delete old data add new data");
        [self deleteStringForKey:aKey];
        SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);
    }
    if (status != noErr) {
    //  NSLog(@"[KeychainAccessor]>>> SecItemAdd result in error:(%d)",(int)status);
    }
}
//查询
+ (NSString *)stringForKey:(NSString *)aKey {
    NSMutableDictionary *query = [NSMutableDictionary dictionary];
    [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge  id)kSecClass];
    [query setObject:(id)aKey forKey:(__bridge id)kSecAttrAccount];
    [query setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef result = nil;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef*)&result);
    if (status != noErr) {
    if (status == errSecItemNotFound) {
        //NSLog(@"[KeychainAccessor]>>> SecItemCopyMatching result NOT-FOUND.");
    } else {
        //NSLog(@"[KeychainAccessor]>>> SecItemCopyMatching result in error:(%d)", (int)status);
    }
    return @"";
    }
    NSData *theValue = [(__bridge NSData*)result copy];
    return [[NSString alloc] initWithData:theValue encoding:NSUTF8StringEncoding];
}   

2.压缩图片到指定尺寸大小

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

3.压缩图片到指定文件大小

//压缩图片到指定文件大小
+ (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;
}

4.截取全屏

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

5.判断邮箱格式

//利用正则表达式验证
+ (BOOL)isAvailableEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES        %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

6.判断手机号格式

//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile{
mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
if (mobile.length != 11)
{
    return NO;
}else{
    NSString *CM_NUM = @"^((13[4-9])|(147)|(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 *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

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.获取几天后的日期

+(NSString *)dateLineWithDay:(NSTimeInterval)day
{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    NSDate * nowDate = [NSDate date];
    NSTimeInterval  interval =24*60*60*day; //day:天数
    NSDate * date1 = [nowDate initWithTimeIntervalSinceNow:interval];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    return [dateFormatter stringFromDate:date1];
}

9.判断是否第一次启动此版本的App

+(BOOL)checkFirstStart
{
    NSString *key = (NSString *)kCFBundleVersionKey;
    NSString *version = [NSBundle mainBundle].infoDictionary[key];
    NSString *saveVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"VKEY"];
    if ([version isEqualToString:saveVersion])
    {
    //不是第一次
    }else{
    //是第一次      
    }
}

暂时整理这么多,后续会持续添加,如果友友们有更好更实用的方法,欢迎联系我!

你可能感兴趣的:(总结iOS开发中常用的辅助方法)