總結(jié)iOS開發(fā)中常用的輔助方法

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.判斷郵箱格式

//利用正則表達(dá)式驗(yàn)證
+ (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.判斷手機(jī)號格式

//判斷手機(jī)號碼格式是否正確
+ (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.獲取當(dāng)前時間

//獲取當(dāng)前時間
//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:天數(shù)
    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{
    //是第一次      
    }
}

暫時整理這么多,后續(xù)會持續(xù)添加,如果友友們有更好更實(shí)用的方法,歡迎聯(lián)系我!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Swift版本點(diǎn)擊這里歡迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh閱讀 25,573評論 7 249
  • 我們?nèi)チ巳齻€博物館~都暗藏在souk里,所以找這三個博物館就花了將近一天的時間,不要以為摩洛哥人幫助是出于好心,到...
    天使熙閱讀 377評論 0 0
  • 今天是多云吧,沒有出門,天氣并不重要,南方的冬天濕冷,那一點(diǎn)點(diǎn)微薄的陽光更像是安慰劑,驅(qū)散一絲心里的寒意。我從不追...
    我就叫袁磊閱讀 212評論 0 0
  • 一、從“信息高速公路”到“物聯(lián)網(wǎng)” 1993年,美國政府宣布實(shí)施一項(xiàng)新的高科技計劃——“國家信息基礎(chǔ)設(shè)施”,旨在以...
    小白話蟲閱讀 506評論 0 1
  • “科科可可”是我的小名。因?yàn)榭瓶票徽剂耍赃x擇了科科可可來注冊。曾經(jīng)一度覺得科科很土、很俗,所以每每被別人逼問小...
    科科可可閱讀 236評論 0 0