1、文字中是否包含表情
+ (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{
returnValue = NO;
}
}
} else if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3) {
returnValue = YES;
}else{
returnValue = NO;
}
} 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;
}else{
returnValue = NO;
}
}
}];
return returnValue;
}
2、邮箱
+ (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];
}
3、身份证号
+ (BOOL)validateIdentityCard: (NSString *)identityCard
{
BOOL flag;
if (identityCard.length <= 0) {
flag = NO;
return flag;
}
NSString *regex2 = @"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
NSString *regex3 = @"^[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)$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
NSPredicate *identityCardPredicate2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex3];
if ([identityCardPredicate evaluateWithObject:identityCard]==YES ||[identityCardPredicate2 evaluateWithObject:identityCard]==YES) {
return YES;
}else{
return NO;
}
}
4、中文名称
+ (BOOL)isChineseName:(NSString *)name{
BOOL isname = false;
for (int i=0; i
5、将视图添加在全屏
+ (void)addWindow:(UIView *)view {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[window addSubview:view];
}
6、将当前时间转换为时间戳
+ (NSString *)timeToTurnTheTimestamp {
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
return [NSString stringWithFormat:@"%0.f", a];
}
7、将某个时间转换为时间戳
+ (NSString *)timeToTurnTheTimestamp:(NSString *) time{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate * needFormatDate = [dateFormatter dateFromString:time];
NSTimeInterval a=[needFormatDate timeIntervalSince1970];
return [NSString stringWithFormat:@"%0.f", a];
}
8、获取设备的ip地址
+ (NSString *)deviceIPAdress {
NSString *address = @"an error occurred when obtaining ip address";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) { // 0 表示获取成功
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;
}
}
freeifaddrs(interfaces);
return address;
}
9、判断手机号
+(BOOL)isPhoneNumber:(NSString *)mobileNum{
if ([mobileNum length] == 0) {
return NO;
}
mobileNum = [mobileNum stringByReplacingOccurrencesOfString:@" " withString:@""];
if (mobileNum.length != 11)
{
return NO;
}else{
/**
* 移动号段正则表达式
*/
NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(17[0,1,3,6,7,8])|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
/**
* 联通号段正则表达式
*/
NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(17[0,1,3,5,6,7,8])|(18[5,6]))\\d{8}|(1709)\\d{7}$";
/**
* 电信号段正则表达式
*/
NSString *CT_NUM = @"^((133)|(153)|(17[0,1,3,6,7,8])|(18[0,1,9]))\\d{8}$";
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
BOOL isMatch1 = [pred1 evaluateWithObject:mobileNum];
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
BOOL isMatch2 = [pred2 evaluateWithObject:mobileNum];
NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
BOOL isMatch3 = [pred3 evaluateWithObject:mobileNum];
if (isMatch1 || isMatch2 || isMatch3) {
return YES;
}else{
return NO;
}
}
}
10、计算字符串Size
+ (CGSize)boundingRectWithSize:(CGSize)size
withString:(NSString *)string
withFont:(UIFont *)font {
return [string boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
}
11、判断是否是同一天
+ (BOOL)isSameDay:(NSDate *)date1 date2:(NSDate *)date2
{
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comp1 = [calendar components:unitFlag fromDate:date1];
NSDateComponents *comp2 = [calendar components:unitFlag fromDate:date2];
return ( ([comp1 day] == [comp2 day]) && ([comp1 month] == [comp2 month]) && ([comp1 year] == [comp2 year]));
}
12、时间比较大小
+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
DLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
if (result == NSOrderedDescending) {
//oneDay > anotherDay
return 1;
}
else if (result == NSOrderedAscending){
//oneDay < anotherDay
return -1;
}
//oneDay = anotherDay
return 0;
}
13、是不是整数
+ (BOOL)isPureInt:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
14、是不是浮点型
+ (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
15、是不是数字
+ (BOOL)isPureIntOrisPureFloat:(NSString *)numberStr{
if( ![self isPureInt:numberStr] && ![self isPureFloat:numberStr])
{
return NO;
}else{
return YES;
}
}
16、是不是周末
+ (BOOL)iscalculateWeek:(NSString *)string{
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyy.MM.dd"];
NSDate *startD =[date dateFromString:string];
NSString *str = [self calculateWeek:startD];
if ([str isEqualToString:@"周日"] || [str isEqualToString:@"周六"] ) {
return YES;
}else{
return NO;
}
}
17、某一天是周几
+ (NSString *)calculateWeek:(NSDate *)date{
//计算week数
NSCalendar * myCalendar = [NSCalendar currentCalendar];
myCalendar.timeZone = [NSTimeZone systemTimeZone];
NSInteger week = [[myCalendar components:NSCalendarUnitWeekday fromDate:date] weekday];
// NSLog(@"week : %zd",week);
switch (week) {
case 1:
{
return @"周日";
}
case 2:
{
return @"周一";
}
case 3:
{
return @"周二";
}
case 4:
{
return @"周三";
}
case 5:
{
return @"周四";
}
case 6:
{
return @"周五";
}
case 7:
{
return @"周六";
}
}
return @"";
}
18、两个时间段相差时分秒
+ (NSString *)dateTimeDifferenceWithStartTime2:(NSString *)startTime endTime:(NSString *)endTime{
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startD =[date dateFromString:startTime];
NSDate *endD = [date dateFromString:endTime];
NSTimeInterval start = [startD timeIntervalSince1970]*1;
NSTimeInterval end = [endD timeIntervalSince1970]*1;
NSTimeInterval value = end - start;
int second = (int)value %60;//秒
int minute = (int)value /60%60;
int house = (int)value / (24 * 3600)%3600;
int day = (int)value / (24 * 3600);
NSString *str = @"";
if (day != 0) {
str = [NSString stringWithFormat:@"%d天%d小时%d分%d秒",day,house,minute,second];
}else if (day==0 && house != 0) {
str = [NSString stringWithFormat:@"%d小时%d分%d秒",house,minute,second];
}else if (day== 0 && house== 0 && minute!=0) {
str = [NSString stringWithFormat:@"%d分%d秒",minute,second];
}else{
str = [NSString stringWithFormat:@"%d秒",second];
}
return str;
}
19、计算多少秒为几天几时几分
+ (NSString *)timeFormatted:(int)totalSeconds
{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
int day = totalSeconds / (24 * 3600);
NSString *str = @"";
if (day != 0) {
str = [NSString stringWithFormat:@"%d天%d小时%d分%d秒",day,hours,minutes,seconds];
}else if (day==0 && hours != 0) {
str = [NSString stringWithFormat:@"%d小时%d分%d秒",hours,minutes,seconds];
}else if (day== 0 && hours== 0 && minutes!=0) {
str = [NSString stringWithFormat:@"%d分%d秒",minutes,seconds];
}else{
str = [NSString stringWithFormat:@"%d秒",seconds];
}
return str;
}
+ (NSString *)timeFormattedSingle:(int)totalSeconds{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
int day = totalSeconds / (24 * 3600);
NSString *str = @"";
if (day != 0) {
str = [NSString stringWithFormat:@"%d天 %d:%d:%d",day,hours,minutes,seconds];
}else if (day==0 && hours != 0) {
str = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds];
}else if (day== 0 && hours== 0 && minutes!=0) {
str = [NSString stringWithFormat:@"%d:%d",minutes,seconds];
}else{
str = [NSString stringWithFormat:@"%d",seconds];
}
return str;
}
19、属性字符串
1、同字体不同色
+ (NSMutableAttributedString *) compareString:(NSString *)firstStr andLast:(NSString *)nextStr withFont:(UIFont *)font withFirstColor:(UIColor *)firstColor withLastColor:(UIColor *)lastcolor{
NSMutableAttributedString * firstPart = [[NSMutableAttributedString alloc] initWithString:firstStr];
NSDictionary * firstAttributes = @{ NSFontAttributeName:font,NSForegroundColorAttributeName:firstColor,};
[firstPart setAttributes:firstAttributes range:NSMakeRange(0,firstPart.length)];
NSMutableAttributedString * secondPart = [[NSMutableAttributedString alloc] initWithString:nextStr];
NSDictionary * secondAttributes = @{NSFontAttributeName:font,NSForegroundColorAttributeName:lastcolor,};
[secondPart setAttributes:secondAttributes range:NSMakeRange(0,secondPart.length)];
[firstPart appendAttributedString:secondPart];
return firstPart;
}
2、同色不同字体
+ (NSMutableAttributedString *) compareString:(NSString *)firstStr andLast:(NSString *)nextStr withColor:(UIColor *)color withFirstFont:(UIFont *)firstFont withLastFont:(UIFont *)lastFont{
NSMutableAttributedString * firstPart = [[NSMutableAttributedString alloc] initWithString:firstStr];
NSDictionary * firstAttributes = @{ NSFontAttributeName:firstFont,NSForegroundColorAttributeName:color,};
[firstPart setAttributes:firstAttributes range:NSMakeRange(0,firstPart.length)];
NSMutableAttributedString * secondPart = [[NSMutableAttributedString alloc] initWithString:nextStr];
NSDictionary * secondAttributes = @{NSFontAttributeName:lastFont,NSForegroundColorAttributeName:color,};
[secondPart setAttributes:secondAttributes range:NSMakeRange(0,secondPart.length)];
[firstPart appendAttributedString:secondPart];
return firstPart;
}
3、不同色不同字体
+ (NSMutableAttributedString *) compareString:(NSString *)firstStr andLast:(NSString *)nextStr withFirstFont:(UIFont *)firstfont withLastFont:(UIFont *)lastfont withFirstColor:(UIColor *)firstColor withLastColor:(UIColor *)lastcolor{
NSMutableAttributedString * firstPart = [[NSMutableAttributedString alloc] initWithString:firstStr];
NSDictionary * firstAttributes = @{ NSFontAttributeName:firstfont,NSForegroundColorAttributeName:firstColor,};
[firstPart setAttributes:firstAttributes range:NSMakeRange(0,firstPart.length)];
NSMutableAttributedString * secondPart = [[NSMutableAttributedString alloc] initWithString:nextStr];
NSDictionary * secondAttributes = @{NSFontAttributeName:lastfont,NSForegroundColorAttributeName:lastcolor,};
[secondPart setAttributes:secondAttributes range:NSMakeRange(0,secondPart.length)];
[firstPart appendAttributedString:secondPart];
return firstPart;
}
20、两个时间段之间的月份
- (NSMutableArray *)createArraywithStart:(NSString *)startString withEnd:(NSString *)endString
{
NSMutableArray * resultArray=[NSMutableArray array];
NSArray * startArray=[startString componentsSeparatedByString:@"-"];
NSArray * endArray=[endString componentsSeparatedByString:@"-"];
if ([[startArray objectAtIndex:0]isEqualToString:[endArray objectAtIndex:0]]) {
for (int i=[[startArray objectAtIndex:1]intValue]; i<=[[endArray objectAtIndex:1]intValue]; i++) {
NSString * yearString=[NSString stringWithFormat:@"%@-%d月",[startArray objectAtIndex:0],i];
[resultArray addObject:yearString];
}
}else if([[startArray objectAtIndex:0] compare:[endArray objectAtIndex:0] options:NSNumericSearch] == NSOrderedAscending){//升
for (int i=[[startArray objectAtIndex:1]intValue]; i<=12; i++) {
NSString * yearString=[NSString stringWithFormat:@"%@-%d月",[startArray objectAtIndex:0],i];
[resultArray addObject:yearString];
}
for (int i=[[startArray objectAtIndex:0]intValue]+1; i<=[[endArray objectAtIndex:0]intValue]-1; i++) {
for (int j=1; j<=12; j++) {
NSString * yearString=[NSString stringWithFormat:@"%d-%d月",i,j];
[resultArray addObject:yearString];
}
}
for (int i=1; i<=[[endArray objectAtIndex:1]intValue]; i++) {
NSString * yearString=[NSString stringWithFormat:@"%@-%d月",[endArray objectAtIndex:0],i];
[resultArray addObject:yearString];
}
}else{
DLog(@"您的结束时间晚于开始时间");
}
return resultArray;
}
- (NSArray *)dateFromeTime:(NSString *)startTime ToTime:(NSString *)lastTime{
NSArray *startArr = [startTime componentsSeparatedByString:@"."];
NSArray *lastArr = [lastTime componentsSeparatedByString:@"."];
NSMutableArray *dates = [[NSMutableArray alloc] init];
NSInteger indexMonth = [startArr[1] integerValue];
NSInteger indexYear = [startArr[0] integerValue];
NSString *first = [NSString stringWithFormat:@"%@.%ld",startArr[0],(long)indexMonth];
[dates addObject:first];
while (([lastArr[0] integerValue] > indexYear) || ([lastArr[0] integerValue] == indexYear && [lastArr[1] integerValue] >= indexMonth))
{
indexMonth++;
if (indexMonth > 12){ // 判断是否大于12月
indexMonth = 1;
indexYear ++;
}
NSString *monthTime = [NSString stringWithFormat:@"%ld.%ld",(long)indexYear,(long)indexMonth];
[dates addObject:monthTime];
}
[dates removeLastObject];
return dates;
}
21、两个时间段之间的天数
- (NSArray *)dateFromeTime:(NSString *)startTime ToTime:(NSString *)lastTime{
NSDateFormatter *date = [NSDateFormatter sharedDateFormatter];
[date setDateFormat:@"yyyy.MM.dd"];
NSDate *startD =[date dateFromString:startTime];
NSDate *endD = [date dateFromString:lastTime];
NSTimeInterval nowTime = [startD timeIntervalSince1970]*1;
NSTimeInterval endTime = [endD timeIntervalSince1970]*1;
NSMutableArray *dates = [[NSMutableArray alloc] init];
NSTimeInterval dayTime = 24*60*60;
double mm = (long long)nowTime % (int)dayTime;
NSTimeInterval time = nowTime - mm;
while (time <= endTime) {
NSString *showOldDate = [date stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
[dates addObject:showOldDate];
time += dayTime;
}
[dates removeObjectAtIndex:0];
[dates addObject:lastTime];
return dates;
}
22、获取网络北京时间,[NSDate date]获取的是设备当前时间
#pragma mark --请求网络时间戳
+ (void)getInternetDateWithSuccess:(void(^)(NSTimeInterval timeInterval))success
failure:(void(^)(NSError *error))failure{
//1.创建URL
NSString *urlString = @"http://m.baidu.com";
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//2.创建request请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString: urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:5];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPMethod:@"GET"];
//3.创建URLSession对象
NSURLSession *session = [NSURLSession sharedSession]; //4.设置数据返回回调的block
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil && response != nil) {
//这么做的原因是简体中文下的手机不能识别“MMM”,只能识别“MM”
NSArray *monthEnglishArray = @[@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sept",@"Sep",@"Oct",@"Nov",@"Dec"];
NSArray *monthNumArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"09",@"10",@"11",@"12"];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *allHeaderFields = [httpResponse allHeaderFields];
NSString *dateStr = [allHeaderFields objectForKey:@"Date"];
dateStr = [dateStr substringFromIndex:5];
dateStr = [dateStr substringToIndex:[dateStr length]-4];
dateStr = [dateStr stringByAppendingString:@" +0000"];
//当前语言是中文的话,识别不了英文缩写
for (NSInteger i = 0 ; i < monthEnglishArray.count ; i++) {
NSString *monthEngStr = monthEnglishArray[i];
NSString *monthNumStr = monthNumArray[i];
dateStr = [dateStr stringByReplacingOccurrencesOfString:monthEngStr withString:monthNumStr];
}
NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
[dMatter setDateFormat:@"dd MM yyyy HH:mm:ss Z"];
NSDate *netDate = [dMatter dateFromString:dateStr];
NSTimeInterval timeInterval = [netDate timeIntervalSince1970];
dispatch_async(dispatch_get_main_queue(), ^{
success(timeInterval);
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
//4、执行网络请求
[task resume];
}