1、改变按钮倒计时与状态
+(void)changeVerifyButtonState:(UIButton *)sender
{
__block int countDown = 120;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if(countDown <= 0)
{
//倒计时结束,关闭
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示
sender.enabled = YES;
sender.backgroundColor = Main_Color;
[sender setTitle:@"重新获取验证码" forState:UIControlStateNormal];
});
}
else
{
NSString *TimeString = [NSString stringWithFormat:@"%.2d", countDown];
dispatch_async(dispatch_get_main_queue(), ^{
[sender setTitle:[NSString stringWithFormat:@"%@秒再次获取",TimeString] forState:UIControlStateNormal];
sender.backgroundColor = MainTwoText_Color;
sender.enabled = NO;
});
countDown--;
}
});
dispatch_resume(timer);
}
2、过滤所有Emoji标签符号
/**过滤所有Emoji标签符号*/
+(BOOL)stringContainEmoji:(NSString *)emoji{
__block BOOL returnValue = NO;
[emoji enumerateSubstringsInRange:NSMakeRange(0, [emoji length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
// surrogate pair
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 {
// non surrogate
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;
}
3、判断手机格式(包括香港手机号的判断)
+(BOOL)validateWithMobile:(NSString *)mobile
{
NSString * phone = @"^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(19[0-9])|(147))\\d{8}$|^(5|6|8|9)\\d{7}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
return [phoneTest evaluateWithObject:mobile];
}
4、判断姓名格式
+(BOOL)validateUserName:(NSString *)name
{
NSString *userNameRegex = @"^[A-Za-z0-9]{3,20}+$";
NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
BOOL B = [userNamePredicate evaluateWithObject:name];
return B;
}
5、判断输入昵称
+(BOOL)validateNickname:(NSString *)nickname
{
NSString *nicknameRegex = @"^[\u4E00-\u9FA5\uf900-\ufa2d·s•]{2,20}$";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
return [passWordPredicate evaluateWithObject:nickname];
}
6、判断邮箱格式
+(BOOL)ValidateEmail:(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];
}
7、判断字符串首字符是否为字母
+(BOOL)JudgeString:(NSString *)string{
NSString *regex = @"[A-Za-z]+";
NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [predicate evaluateWithObject:string];
}
8、时间戳转时间
/**1.时间戳转换成时间*/
+ (NSString *)dateWithString:(NSString *)str Format:(NSString *)format
{
NSTimeInterval time = [str doubleValue];
/** [[NSDate date] timeIntervalSince1970]*1000;*/
NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormatter setDateFormat:format];//设定时间格式,这里可以设置成自己需要的格式
NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
return currentDateStr;
}
/**2.时间戳转换时间-毫秒*/
+ (NSString *)dateMSWithString:(NSString *)str Format:(NSString *)format
{
NSTimeInterval time = [str doubleValue]/1000;
/** [[NSDate date] timeIntervalSince1970]*1000;*/
NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormatter setDateFormat:format];//设定时间格式,这里可以设置成自己需要的格式
NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
return currentDateStr;
}
/**3.转换成时间*/
+(NSString *)dateWithDate:(NSDate *)date Format:(NSString *)format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormatter setDateFormat:format];//设定时间格式,这里可以设置成自己需要的格式
NSString *currentDateStr = [dateFormatter stringFromDate:date];
return currentDateStr;
}
/**4.当前时间戳转换成时间*/
+ (NSString *)currentDateWithFormat:(NSString *)format
{
NSDate *detaildate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormatter setDateFormat:format];//设定时间格式,这里可以设置成自己需要的格式
NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
return currentDateStr;
}
9、时间戳转星期
+(NSString*)getWeekDay:(NSString*)currentStr
{
NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate*date =[dateFormat dateFromString:currentStr];
NSArray*weekdays = [NSArray arrayWithObjects: [NSNull null],@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",nil];
NSCalendar*calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSTimeZone*timeZone = [[NSTimeZone alloc]initWithName:@"Asia/Shanghai"];
[calendar setTimeZone: timeZone];
NSCalendarUnit calendarUnit =NSCalendarUnitWeekday;
NSDateComponents*theComponents = [calendar components:calendarUnit fromDate:date];
return [weekdays objectAtIndex:theComponents.weekday];
}
10、 NSString转NSDate
+ (NSDate *)dateWithdate:(NSString *)str Format:(NSString *)format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
[dateFormatter setDateFormat:format];//设定时间格式,这里可以设置成自己需要的格式
NSDate * mainDate = [dateFormatter dateFromString:str];
return mainDate;
}
11、 判断系统通知是否打开
+(BOOL)openThePushNotification{
if (IOS8) {//IOS8写的宏
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
// 未打开通知//这个是个自定义的alertView 当用户没有打开推送时 会弹出 可以替换成自己项目里面的弹框
if (IOS8) {//iOS8以后跳转到设置界面的代码也出现了变化 下面这段代码是直接跳转到APP的设置界面
//跳入当前App设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}else{
//适配iOS7 ,跳入系统设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:General&path=Reset"]];
}
return NO;
}else{
return YES;
}
}else{ // ios7
if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes] == UIUserNotificationTypeNone) {
if (IOS8) {
//跳入当前App设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}else{
//适配iOS7 ,跳入系统设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:General&path=Reset"]];
}
return NO;
}else{
return YES;
}
}
}
12、获取手机型号
+ (NSString *)deviceVersion
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
if ([platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
if ([platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus";
if ([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
if ([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
if ([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
if ([platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
if ([platform isEqualToString:@"iPhone11,4"]) return @"iPhone XS Max";
if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
return platform;
}
13、字典转JSON
/**
* 字典转JSON
*/
+ (NSString *)dictionaryToJson:(NSDictionary *)dict
{
BOOL isValidJSONObject = [NSJSONSerialization isValidJSONObject:dict];
if (isValidJSONObject)
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return nil;
}
/*
* JSON转字典
*/
+ (NSDictionary *)jsonToDictionary:(NSString *)jsonString
{
if (jsonString == nil)
{
return nil;
}
// NSLog(@"%@",jsonString);
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
// NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
14、判断银行卡是否合法
+(BOOL)checkBankCardNumber:(NSString *)cardNumber
{
int oddSum = 0; // 奇数和
int evenSum = 0; // 偶数和
int allSum = 0; // 总和
// 循环加和
for (NSInteger i = 1; i <= cardNumber.length; i++)
{
NSString *theNumber = [cardNumber substringWithRange:NSMakeRange(cardNumber.length-i, 1)];
int lastNumber = [theNumber intValue];
if (i%2 == 0)
{
// 偶数位
lastNumber *= 2;
if (lastNumber > 9)
{
lastNumber -=9;
}
evenSum += lastNumber;
}
else
{
// 奇数位
oddSum += lastNumber;
}
}
allSum = oddSum + evenSum;
// 是否合法
if (allSum%10 == 0)
{
return YES;
}
else
{
return NO;
}
}
15、过滤指定字符
+(NSString*)RemoveSpecialCharacter: (NSString *)str {
NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @",.?、 ~¥#&<>《》()[]{}【】^@/£¤|§¨「」『』¢¬ ̄~@#&*()——+|《》$_€"]];
if (urgentRange.location != NSNotFound)
{
return [self RemoveSpecialCharacter:[str stringByReplacingCharactersInRange:urgentRange withString:@""]];
}
return str;
}
16、判断密码格式
+(BOOL)validateWithPassword:(NSString *)password
{
//密码只包含字母,数字,字符中至少两种
NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}$";
NSPredicate * pas= [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [pas evaluateWithObject:password];
}
17、字符串替换
+(NSString *)StringChooseString:(NSString *)chooseStr{
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\"."];
NSString *trimmedString = [chooseStr stringByTrimmingCharactersInSet:set];
// NSLog(@"DELECT----%@",trimmedString);
NSString *str = [trimmedString stringByReplacingOccurrencesOfString:@"\"," withString:@"、"];//替换字符
NSString * twoStr = [str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSString * three = [twoStr stringByReplacingOccurrencesOfString:@"." withString:@""];
// NSLog(@"DELECTONE----%@",three);
return three;
}
18、字典按升序排序
+ (NSString *)stringWithAscendingOrderDict:(NSDictionary*)dict
{
NSArray*keys = [dict allKeys];
NSArray*sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2)
{
return[obj1 compare:obj2 options:NSNumericSearch];//正序
}];
NSString*str =@"";
for(NSString*categoryId in sortedArray)
{
id value = [dict objectForKey:categoryId];
if ([value isKindOfClass:[NSDictionary class]])
{
value = [self stringWithAscendingOrderDict:value];
}
if ([str length] !=0)
{
str = [str stringByAppendingString:@"&"];
}
str = [str stringByAppendingFormat:@"%@=%@",categoryId,value];
}
return str;
}
19、图片压缩
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
20、显示原生弹框
+ (void)showInfo:(NSString *)info VC:(UIViewController *)VC
{
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:info preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertVC addAction:okAction];
[VC presentViewController:alertVC animated:YES completion:nil];
}
21、匹配身份证号码
+ (BOOL)matchesWithIDCardNumber:(NSString *)idNumber
{
return [self matchesWithFormatString:@"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$" tagaetStr:idNumber];
}
22、每隔4个字符添加一个空格的字符串算法
+ (NSString *)dealWithString:(NSString *)number
{
NSString *doneTitle = @"";
int count = 0;
for (int i = 0; i < number.length; i++) {
count++;
doneTitle = [doneTitle stringByAppendingString:[number substringWithRange:NSMakeRange(i, 1)]];
if (count == 4) {
doneTitle = [NSString stringWithFormat:@"%@ ", doneTitle];
count = 0;
}
}
// NSLog(@"%@", doneTitle);
return doneTitle;
}
23、字符串转拼音
+(NSString *)transformToPinyin:(NSString *)aString
{
//转成了可变字符串
NSMutableString *str = [NSMutableString stringWithString:aString];
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再转换为不带声调的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
NSMutableString *allString = [NSMutableString new];
int count = 0;
for (int i = 0; i < pinyinArray.count; i++)
{
for(int i = 0; i < pinyinArray.count;i++)
{
if (i == count) {
[allString appendString:@"#"];
//区分第几个字母
}
[allString appendFormat:@"%@",pinyinArray[i]];
}
[allString appendString:@","];
count ++;
}
NSMutableString *initialStr = [NSMutableString new];
//拼音首字母
for (NSString *s in pinyinArray)
{
if (s.length > 0)
{
[initialStr appendString: [s substringToIndex:1]];
}
}
[allString appendFormat:@"#%@",initialStr];
[allString appendFormat:@",#%@",aString];
return allString;
}
24、判断字符串是否为整形,若字符串是一个字符,则判断是否是数字
+ (BOOL) deptNumInputShouldNumber:(NSString *)str
{
if (str.length == 0) {
return NO;
}
NSString *regex = @"[0-9]*";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if ([pred evaluateWithObject:str]) {
return YES;
}
return NO;
}
限制TextField只能输入数字和字母
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.searchEdTextField.rightTextField) {
NSUInteger lengthOfString = string.length;
//lengthOfString的值始终为1
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
unichar character = [string characterAtIndex:loopIndex];
//将输入的值转化为ASCII值(即内部索引值),可以参考ASCII表
// 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
if (character < 48) return NO; // 48 unichar for 0
if (character > 57 && character < 65) return NO; //
if (character > 90 && character < 97) return NO;
if (character > 122) return NO;
}
// Check for total length
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 11) {
return NO;//限制长度
}
return YES;
}
return YES;
}
彩色图片转灰度
+(UIImage *)changeGrayImage:(UIImage *)oldImage
{
int bitmapInfo = kCGImageAlphaNone;
int width = oldImage.size.width;
int height = oldImage.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate (nil,
width,
height,
8,
0,
colorSpace,
bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return nil;
}
CGContextDrawImage(context,
CGRectMake(0, 0, width, height), oldImage.CGImage);
UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
return grayImage;
}
地址
网友评论