iOS常用的封装方法

//

//  Tool.m

//  YuTongTianXia

//

//  Created by 合一网络 on 16/3/17.

//  Copyright © 2016年 合一网络. All rights reserved.

//

 

#import "Tool.h"

#import "BlockButton.h"

#import "LoginViewController.h"

 

//sha1 加密之前引入文件

#import <CommonCrypto/CommonDigest.h>

 

 

@implementation Tool

 

#pragma mark  密码sha1加密

+(NSString * )sha1WithInputStr:(NSString * )inputStr{

    const char * cstr = [inputStr cStringUsingEncoding:NSUTF8StringEncoding];

    NSData * data = [NSData dataWithBytes:cstr length:inputStr.length];

    

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, (unsigned int)data.length, digest);

    NSMutableString * outputStr = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

    for (int i = 0 ; i< CC_SHA1_DIGEST_LENGTH; i++) {

        [outputStr appendFormat:@"%02x",digest[i]];

    }

    return outputStr;

}

 

#pragma mark  MD5加密

+ (NSString *) md5:(NSString *) input {

    const char *cStr = [input UTF8String];

    unsigned char digest[CC_MD5_DIGEST_LENGTH];

    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call

    

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

    

    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)

        [output appendFormat:@"%02x", digest[i]];

    

    return  output;

}

 

#pragma mark 产生32位随机字符串

+(NSString *)getRandomStringWithret32bitString

 

{

    char data[32];

    

    for (int x=0;x<32;data[x++] = (char)('A' + (arc4random_uniform(26))));

    

    return [[NSString alloc] initWithBytes:data length:32 encoding:NSUTF8StringEncoding];

    

}

 

#pragma mark  正则判断手机号是否正确

+ (BOOL)validateNumber:(NSString *) textString

{

    NSString* number=@"^1[3|4|5|7|8][0-9]\\d{8}$";

    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];

    return [numberPre evaluateWithObject:textString];

}

 

#pragma mark 正则判断身份证号

+ (BOOL) validateIdentityCard: (NSString *)identityCard

{

    BOOL flag;

    if (identityCard.length <= 0) {

        flag = NO;

        return flag;

    }

    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";

    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];

    return [identityCardPredicate evaluateWithObject:identityCard];

}

 

 

 

#pragma mark 正则判断快递单号

+ (BOOL) validateEMSnumber: (NSString *)EMSnumber

{

    BOOL flag;

    if (EMSnumber.length <= 0) {

        flag = NO;

        return flag;

    }

    NSString * reg = @"^[0-9a-zA-Z]{10,}$";

    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];

    return [identityCardPredicate evaluateWithObject:EMSnumber];

}

 

 

 

#pragma mark 正则判断取现金额

+ (BOOL) validateCashMoney: (NSString *)cashMoney

{

    BOOL flag;

    if (cashMoney.length <= 0) {

        flag = NO;

        return flag;

    }

    NSString * reg = @"^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){1,2})?$";

    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];

    return [identityCardPredicate evaluateWithObject:cashMoney];

}

 

#pragma mark - 正则判断100的整数倍

+ (BOOL)judge100IntegerTimes:(NSString *)str

{

    NSString *remainderStr = [NSString stringWithFormat:@"%d", [str intValue] % 100];

    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0]$"];

    return [numberPre evaluateWithObject:remainderStr];

    

}

 

#pragma mark 正则判断登录密码是否正确(6-20位数字字母结合)

+ (BOOL)validateNumberOrLetter:(NSString *) textString

{

    BOOL result = false;

    if ([textString length] >= 6){

        

        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";

        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

        result = [pred evaluateWithObject:textString];

    }

    return result;

}

 

 

#pragma mark 正则简单判断银行卡号是否正确(16-19位数字)

+ (BOOL)validateBankCardNumber:(NSString *)textString

{

    NSString* number=@"^([0-9]{16}|[0-9]{19})$";

    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];

    return [numberPre evaluateWithObject:textString];

}

 

#pragma mark  判断输入含有表情

+ (BOOL)stringContainsEmoji:(NSString *)string

{

    __block BOOL returnValue = NO;

    

    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])

                               options:NSStringEnumerationByComposedCharacterSequences

                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {

                                const unichar hs = [substring characterAtIndex:0];

                                if (0xd800 <= hs && hs <= 0xdbff) {

                                    if (substring.length > 1) {

                                        const unichar ls = [substring characterAtIndex:1];

                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;

                                        if (0x1d000 <= uc && uc <= 0x1f77f) {

                                            returnValue = YES;

                                        }

                                    }

                                } else if (substring.length > 1) {

                                    const unichar ls = [substring characterAtIndex:1];

                                    if (ls == 0x20e3) {

                                        returnValue = YES;

                                    }

                                } else {

                                    if (0x2100 <= hs && hs <= 0x27ff) {

                                        returnValue = YES;

                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {

                                        returnValue = YES;

                                    } else if (0x2934 <= hs && hs <= 0x2935) {

                                        returnValue = YES;

                                    } else if (0x3297 <= hs && hs <= 0x3299) {

                                        returnValue = YES;

                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {

                                        returnValue = YES;

                                    }

                                }

                            }];

    

    return returnValue;

}

 

#pragma mark 手机号码中间变*

+(NSString * )cipherchangeText:(NSString * )changetext firstOne:(NSInteger )firstOne lenght:(NSInteger)lenght{

    NSString * number = [changetext stringByReplacingCharactersInRange:NSMakeRange(firstOne, lenght) withString:@"****"];

    return number;

}

 

 

#pragma mark 获取手机UUID

+(NSString * )uuid{

    NSString * uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

    return uuid;

}

 

 

#pragma mark 自适应高度

+(CGRect)sizeOfText:(NSString * )text Width:(CGFloat )width Font:(CGFloat)fontFloat{

    NSDictionary * textDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontFloat],NSFontAttributeName, nil];

    CGRect rect  = [text boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:textDic context:nil];

    return rect;

}

 

#pragma mark 设置行间距

+(CGFloat)RowIntevalWithText:(NSString * )text inteval:(NSInteger)inteval addLabel:(UILabel * )label{

    NSString *cLabelString = text; //文本文字

    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:cLabelString];

    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];

    

    [paragraphStyle1 setLineSpacing:inteval];//行间距

    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [cLabelString length])];

    [label setAttributedText:attributedString1];

    [label sizeToFit];

    

    CGFloat contentHeight = label.bounds.size.height;

    return contentHeight;

}

 

 

#pragma mark  自适应宽度

+(CGRect)sizeOfText:(NSString * )text Height:(CGFloat)height Font:(CGFloat)fontFloat{

    NSDictionary * textDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontFloat],NSFontAttributeName, nil];

    CGRect rect = [text boundingRectWithSize:CGSizeMake(0, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:textDic context:nil];

    return rect;

}

 

 

#pragma mark 加载图

+(MBProgressHUD * )creatLoadMBProgressHUDWithView:(id)view{

    MBProgressHUD * hud = [[MBProgressHUD alloc]init];

    [view addSubview:hud];

    hud.labelText = @"加载中...";

    hud.mode = MBProgressHUDModeIndeterminate;

    hud.dimBackground = NO;

    [hud show:YES];

    return hud;

}

 

#pragma mark 短暂提示

+(MBProgressHUD * )createTisMBProgressHUDWithView:(id)view withMessage:(NSString * )message{

    MBProgressHUD *hud = [[MBProgressHUD alloc] init];

    [view addSubview:hud];

    hud.labelText = message;

    hud.mode = MBProgressHUDModeText;

    hud.dimBackground = NO;

    [hud show:YES];

    return hud;

}

 

 

#pragma mark 创建一条分行分割线

+ (void)createRowLineLabelonView:(UIView * )view{

    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(view.frame) - 0.5, Width_FullScreen - 15, 0.5)];

    lineView.backgroundColor =UIColorFromRGB(240, 240, 240);

    [view addSubview:lineView];

}

 

#pragma mark 创建一条分区分割线

+ (void)createSectionLineLabelonView:(UIView * )view{

    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame) -0.5, Width_FullScreen , 0.5)];

    lineView.backgroundColor = UIColorFromRGB(224, 224, 224);

    

    [view addSubview:lineView];

}

 

#pragma mark 创建一个分区间隔(第一个分区)

+(UIView * )createFirstSectionJiangeViewWithBackgroungColro:(UIColor * )color{

    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width_FullScreen, 5)];

    lineView.backgroundColor = color;

    [self createSectionLineLabelonView:lineView];//下面一条线

    return lineView;

}

 

#pragma mark 创建一个分区间隔(其他分区)

+(UIView * )createOthersSectionJiangeViewWithBackgroungColro:(UIColor * )color{

    UIView * aview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width_FullScreen, 5)];

    aview.backgroundColor = color;

    UIView * lineView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Width_FullScreen , 1)];

    lineView.backgroundColor = UIColorFromRGB(224, 224, 224);

    [aview addSubview:lineView];  //上面一条线

    

    [self createSectionLineLabelonView:aview];//下面一条线

    return aview;

}

 

#pragma mark 按钮圆角

+ (void)CreateButtonCornerRudios:(UIButton *)button WithColor:(UIColor *)Color{

    button.layer.masksToBounds = YES;

    button.layer.cornerRadius = 3;

    button.layer.borderWidth = 0.5;

    button.layer.borderColor = [Color CGColor];

}

 

 

#pragma mark 创建从0分割线

+(UILabel *)createSepLabelFromzero:(CGFloat)Y addView:(UIView *)view{

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, Y, Width_FullScreen, 0.5)];

    label.backgroundColor = SeparationColor;

    [view addSubview:label];

    return label;

}

 

#pragma mark 创建从15分割线

+(UILabel *)createSepLabelFromfifteen:(CGFloat)Y addView:(UIView *)view{

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, Y, Width_FullScreen-15, 0.5)];

    label.backgroundColor = SeparationColorShallow;

    [view addSubview:label];

    return label;

}

 

 

#pragma mark  图片等比压缩

+ (CGFloat)zoomImageScaleWithImage:(UIImage * )image withWidth:(CGFloat )width

{

    UIImage *newImage;

    

    //判断如果图片的SIZE的宽度大于屏幕的宽度就让它压缩

//    if (image.size.width > width) {

        //开始压缩图片

        CGSize size = image.size;

        

        UIGraphicsBeginImageContext(CGSizeMake(width, width * size.height / size.width));

        

        [image drawInRect:CGRectMake(0, 0, width, width * size.height / size.width)];

        

        newImage = UIGraphicsGetImageFromCurrentImageContext();

        

        UIGraphicsEndImageContext();

        

 

//    }

        return newImage.size.height;

}

 

#pragma mark 创建回收键盘图标

+ (void)createReciveKeyBoardToolBarWithView:(id)view{//回收键盘

    UIView * aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Width_FullScreen, 30)];

    aView.backgroundColor = nil;

    

    BlockButton * btn = [BlockButton buttonWithType:UIButtonTypeCustom];

    btn.frame = CGRectMake(Width_FullScreen - 35 , 2, 30, 25);

    [btn setImage:[UIImage imageNamed:@"closekeyboard"] forState:UIControlStateNormal];

    [btn setBlock:^(BlockButton * btn){

        

        [view endEditing:YES];

                

    }];

    

    [aView addSubview:btn];

    [view setInputAccessoryView:aView];

    

}

 

 

#pragma mark 两个时间的时间差

+ (NSTimeInterval)intervalFromLastDate: (NSString *) dateString1  toTheDate:(NSString *) dateString2{

    NSArray *timeArray1=[dateString1 componentsSeparatedByString:@"."];

    dateString1=[timeArray1 objectAtIndex:0];

    

    NSArray *timeArray2=[dateString2 componentsSeparatedByString:@"."];

    dateString2=[timeArray2 objectAtIndex:0];

    

    NSLog(@"%@.....%@",dateString1,dateString2);

    NSDateFormatter *date=[[NSDateFormatter alloc] init];

    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    

    NSDate *d1=[date dateFromString:dateString1];

    

    NSTimeInterval late1=[d1 timeIntervalSince1970]*1;

    

    NSDate *d2=[date dateFromString:dateString2];

    

    NSTimeInterval late2=[d2 timeIntervalSince1970]*1;

    

    NSTimeInterval cha=late2-late1;

    //    NSString *timeString=@"";

    //    NSString *house=@"";

    //    NSString *min=@"";

    //    NSString *sen=@"";

    //

    //    sen = [NSString stringWithFormat:@"%d", (int)cha%60];

    //    //        min = [min substringToIndex:min.length-7];

    //    //    秒

    //    sen=[NSString stringWithFormat:@"%@", sen];

    //

    //    min = [NSString stringWithFormat:@"%d", (int)cha/60%60];

    //    //        min = [min substringToIndex:min.length-7];

    //    //    分

    //    min=[NSString stringWithFormat:@"%@", min];

    //

    //    //    小时

    //    house = [NSString stringWithFormat:@"%d", (int)cha/3600];

    //    //        house = [house substringToIndex:house.length-7];

    //    house=[NSString stringWithFormat:@"%@", house];

    //

    //    timeString=[NSString stringWithFormat:@"%@:%@:%@",house,min,sen];

    //

    //    return timeString;

    return cha;

 

}

 

#pragma mark 监听键盘弹出

+ (void)keyboardShowChangeFrameWithUnderTheView:(UIView * )view backgroundView:(UIView * )bgView{

    // 页面根据键盘的弹出动态变化

    __block __weak id showobserver;

    showobserver = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {

        CGRect keyBoardRect = [[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

        

        int height2 = Height_FullScreen -  keyBoardRect.size.height;

        NSLog(@"--- %d ---",height2);

        int height3 = CGRectGetMaxY(view.frame); //键盘刚好停留在此控件下面

        NSLog(@"--- %d ---",height3);

        

        if (height2 <= height3) {

            [UIView animateWithDuration:0.25 animations:^{

                bgView.frame = CGRectMake(0, 0, Width_FullScreen, Height_FullScreen);

            } completion:^(BOOL finished) {

                bgView.frame = CGRectMake(0, - (height3 - height2), Width_FullScreen, Height_FullScreen + height3 - height2);

            }];

        }else{

            bgView.frame = CGRectMake(0, 0, Width_FullScreen, Height_FullScreen);

        }

        

        if (showobserver) {

            [[NSNotificationCenter defaultCenter] removeObserver:showobserver];

        }

    }];

    

    

 

    

}

 

#pragma mark 监听键盘消失

+ (void)keyboardDismissChangeFrameWithbackgroundView:(UIView * )bgView{

     __block __weak id dismissobserver;

     dismissobserver = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {

            bgView.frame = CGRectMake(0, 0, Width_FullScreen, Height_FullScreen);

         

//         if (dismissobserver) {

//             [[NSNotificationCenter defaultCenter] removeObserver:dismissobserver];

//         }

//         

        }];

    

}

 

 

#pragma mark - 无数据图

+ (void  )NoDataPictureOnView:(UIView * )bgView {

    UIView * aview = [[UIView alloc]initWithFrame:bgView.bounds];

    aview.backgroundColor = [UIColor whiteColor];

    [bgView addSubview:aview];

     

    UIImageView * image = [UITool createImageViewFrame:CGRectMake((Width_FullScreen - 150) / 2, (Height_FullScreen - 230 ) / 2, 150, 150) imageName:@"无数据图"];

    [aview addSubview:image];

    

}

 

 

#pragma mark - 请求失败,重新加载数据

+ (void  )ReGetDataSourceOnView:(UIView * )bgView secondView:(UIView * )secondView point:(void(^)())point{

 

    secondView.hidden = YES;

    UIView * aview = [[UIView alloc]initWithFrame:bgView.bounds];

    aview.backgroundColor = [UIColor whiteColor];

    [bgView addSubview:aview];

    

    BlockButton * btn = [BlockButton buttonWithType:UIButtonTypeCustom];

    btn.frame = CGRectMake((Width_FullScreen - 150) / 2, (bgView.bounds.size.height -230 ) / 2, 150, 150);

    [btn setImage:[UIImage imageNamed:@"断网图"] forState:UIControlStateNormal];

    [btn setBlock:^(BlockButton * sender){

        [aview removeFromSuperview];

        

        point();

    }];

    

    [aview addSubview:btn];

    

}

 

 

#pragma mark - 登录/未登录 情况下的事件

+(void)JudgeLoginAction:(void(^)())login NotLoginAction:(void(^)())noLogin{

    NSString * str = ISLOGIN;

    if ([str isEqualToString:@"1"]) {//登录情况下进行的操作

        login();

    }else if ([str isEqualToString:@"0"]){//未登录情况下进行的操作

        noLogin();

    }

}

 

 

#pragma mark 跳转到登录界面

+ (void)jumpLoginViewController:(UIViewController * )vc{

    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"ErrorToken"];

    [[NSUserDefaults standardUserDefaults] synchronize];

    

    LoginViewController *login = [[LoginViewController alloc]init];

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];

    [vc presentViewController:nav animated:YES completion:nil];

}

 

#pragma mark - 判断输入空格

+ (BOOL) isEmpty:(NSString *) str {

    if (!str) {

        return true;

    } else {

        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];

        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];

        if ([trimedString length] == 0) {

            return true;

        } else {

            return false;

        }

    }

}

 

#pragma mark - 获取当前控制器

+ (UIViewController *)getCurrentVC

{

    UIViewController *result = nil;

    

    UIWindow * window = [[UIApplication sharedApplication] keyWindow];

    if (window.windowLevel != UIWindowLevelNormal)

    {

        NSArray *windows = [[UIApplication sharedApplication] windows];

        for(UIWindow * tmpWin in windows)

        {

            if (tmpWin.windowLevel == UIWindowLevelNormal)

            {

                window = tmpWin;

                break;

            }

        }

    }

    

    UIView *frontView = [[window subviews] objectAtIndex:0];

    id nextResponder = [frontView nextResponder];

    

    if ([nextResponder isKindOfClass:[UIViewController class]])

        result = nextResponder;

    else

        result = window.rootViewController;

    

    return result;

}

 

@end

 

posted @ 2016-09-26 15:45  琼极一生  阅读(600)  评论(0编辑  收藏  举报