1,过滤html中的标签,返回字符串:
+ (NSString *)removeHTML2:(NSString *)html{
//过滤nsstring中html标签
NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
NSMutableArray *componentsToKeep = [NSMutableArray array];
for (int i = 0; i < [components count]; i = i + 2) {
[componentsToKeep addObject:[components objectAtIndex:i]];
}
NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
return plainText;
}
2,ios设备获取自身IP:
//add #include <sys/socket.h>
+ (NSString*) getIPAddress
{
NSString* address;
struct ifaddrs *interfaces = nil;
// get all our interfaces and find the one that corresponds to wifi
if (!getifaddrs(&interfaces))
{
for (struct ifaddrs* addr = interfaces; addr != NULL; addr = addr->ifa_next)
{
if (([[NSString stringWithUTF8String:addr->ifa_name] isEqualToString:@"en0"]) &&
(addr->ifa_addr->sa_family == AF_INET))
{
struct sockaddr_in* sa = (struct sockaddr_in*) addr->ifa_addr;
address = [NSString stringWithUTF8String:inet_ntoa(sa->sin_addr)];
break;
}
}
}
freeifaddrs(interfaces);
return address;
}
3,另外一种获取IP的方法;
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
//
- (NSArray *)getIpAddresses {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) return nil;
NSMutableArray *ips = [NSMutableArray array];
int BUFFERSIZE = 4096;
struct ifconf ifc;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifreq *ifr, ifrcopy;
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
ifr = (struct ifreq *)ptr;
int len = sizeof(struct sockaddr);
if (ifr->ifr_addr.sa_len > len) {
len = ifr->ifr_addr.sa_len;
}
ptr += sizeof(ifr->ifr_name) + len;
if (ifr->ifr_addr.sa_family != AF_INET) continue;
if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0;
if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) continue;
memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
ifrcopy = *ifr;
ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
if ((ifrcopy.ifr_flags & IFF_UP) == 0) continue;
NSString *ip = [NSString stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);
return ips;
}
//获取的数组两个值,第一个是本地地址,127.0.0.1也就是localhost,第二个是路由器DNS分配的公网地址。
4,去掉字符串中的空格。
// //stringByReplacingOccurrencesOfString字符串替换方法,将空格替换为空 NSString *string = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""]; //去掉左右两边的空格 NSString *string = [sourceString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; //去掉左右两边的空格和换行 NSString *string = [sourceString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
5,NSString转换成char类型。
//
//NSString转换 char *
NSString *str4 = @"啊啊啊啊啊";
const char *cstr = [str4 UTF8String];//加const 里边内容不能改变。
printf("%s",cstr);
//因为nsstring是不可变字符串。cstr就是指向字符数组的一个指针。
//将char类型数组转换为nsstring类型的。
NSString *string = [[NSString alloc] initWithCString:(const char*)cstr encoding:NSUTF8StringEncoding];
NSLog(@"string - - %@",string);
6,将字符串转换成数组
//
NSString *sourceStr = @"a,c,d,f,e,g";
NSArray *strarr = [sourceStr componentsSeparatedByString:@“,”];//通过,进行分割,元素里则没有,逗号。
//
/*===数组转换成字符串===*/
//将一个数组转换成一个字符串,通过指定的字符进行分割。两个参数,第一个是要数组,第二个是用什么字符串分割。
NSMutableString * stringFromArray(NSArray * array,NSString * string){
NSMutableString *resultString = [NSMutableString string];
for (int i = 0; i < [array count]; i++) {
[resultString appendString:array[i]];
if(i < [array count] - 1){
[resultString appendString:string];
}
}
return resultString;
}
7,通过属性获取当前属性的类型。
//
static const char * getPropertyType(objc_property_t property) {
const char *attributes = property_getAttributes(property);
char buffer[1 + strlen(attributes)];
strcpy(buffer, attributes);
char *state = buffer, *attribute;
while ((attribute = strsep(&state, ",")) != NULL) {
if (attribute[0] == 'T' && attribute[1] != '@') {
// it's a C primitive type:
/*
if you want a list of what will be returned for these primitives, search online for
"objective-c" "Property Attribute Description Examples"
apple docs list plenty of examples of what you get for int "i", long "l", unsigned "I", struct, etc.
*/
return (const char *)[[NSData dataWithBytes:(attribute + 1) length:strlen(attribute) - 1] bytes];
}
else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) {
// it's an ObjC id type:
return "id";
}
else if (attribute[0] == 'T' && attribute[1] == '@') {
// it's another ObjC object type:
return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
}
}
return "";
}
8,sqlite3判断当前库中数据表是否存在:
//
//判断当前数据库是否有此表
- (BOOL)isExistTable:(NSString *)tableName
{
int exResult = NO;
NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) as 'count' FROM sqlite_master where type='table' and name='%@';",tableName];
const char *sql_stmt = [sql UTF8String];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, sql_stmt, -1, &statement, nil) == SQLITE_OK){
exResult = sqlite3_step(statement) == SQLITE_ROW;
NSInteger count= sqlite3_column_int(statement, 0);
exResult = count == 1 ? YES : NO;
}else{
exResult = NO;
}
return exResult;
}
9,NSData转换NSArray,相互转换:
// NSArray *tmpArray = @[@"1",@"2",@"3"]; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:tmpArray]; NSArray *exchangeArray = NSKeyedUnarchiver unarchiveObjectWithData:data];
10,分别获取当前时间的年,月,日,周等分离数据。
//
+ (NSDateComponents *)nowDateComponents
{
NSDate *dt = [NSDate date];
NSCalendar *cl = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger flag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal;
return [cl components:flag fromDate:dt];
}
//
NSDateComponents *comp = [PublicFunction nowDateComponents];
NSString *weekDay = [NSString string];
switch (comp.weekday) {
case 1:
weekDay = @"日";
break;
case 2:
weekDay = @"一";
break;
case 3:
weekDay = @"二";
break;
case 4:
weekDay = @"三";
break;
case 5:
weekDay = @"四";
break;
case 6:
weekDay = @"五";
break;
case 7:
weekDay = @"六";
break;
default:
break;
}
NSString *dateText = [NSString stringWithFormat:@"%ld月%ld日 星期%@",comp.month,comp.day,weekDay];
11,NSString改变字符串的大小写:
//字符串所有字符变为小写
NSString *lowerCaseString2 = testString.lowercaseString;
//字符串所有字符变为大写
NSString *upperCaseString2 = lowerCaseString1.uppercaseString;
12,UIView转换成UIImage。
//
-(UIImage*)convertViewToImage
{
CGSize size = self.bounds.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)screenshotWithRect:(CGRect)rect optionScale:(CGFloat)scale
{
CGFloat optionScale = scale <= 0 ? [UIScreen mainScreen].scale : scale;
UIGraphicsBeginImageContextWithOptions(rect.size, NO, optionScale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (context == NULL)
{
return nil;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
/*
if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
//截view
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
}else
{
//截view.layer
[self.layer renderInContext:context];
}
*/
[self.layer renderInContext:context];
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
13,获取农历的日历
+ (NSDictionary *)LunarForSolar
{
//天干名称
NSArray *cTianGan = [NSArray arrayWithObjects:@"甲",@"乙",@"丙",@"丁",@"戊",@"己",@"庚",@"辛",@"壬",@"癸", nil];
//地支名称
NSArray *cDiZhi = [NSArray arrayWithObjects:@"子",@"丑",@"寅",@"卯",@"辰",@"巳",@"午",@"未",@"申",@"酉",@"戌",@"亥",nil];
//属相名称
NSArray *cShuXiang = [NSArray arrayWithObjects:@"鼠",@"牛",@"虎",@"兔",@"龙",@"蛇",@"马",@"羊",@"猴",@"鸡",@"狗",@"猪",nil];
//农历日期名
NSArray *cDayName = [NSArray arrayWithObjects:@"*",@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十",nil];
//农历月份名
NSArray *cMonName = [NSArray arrayWithObjects:@"*",@"正",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"十一",@"腊",nil];
//公历每月前面的天数
const int wMonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
//农历数据
const int wNongliData[100] = {2635,333387,1701,1748,267701,694,2391,133423,1175,396438
,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877};
static NSInteger wCurYear,wCurMonth,wCurDay;
static NSInteger nTheDate,nIsEnd,m,k,n,i,nBit;
//取当前公历年、月、日
NSDateComponents *components = [self nowDateComponents];
// [[NSCalendarcurrent Calendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnitfromDate:solarDate];
wCurYear = [components year];
wCurMonth = [components month];
wCurDay = [components day];
//计算到初始时间1921年2月8日的天数:1921-2-8(正月初一)
nTheDate = (wCurYear - 1921) * 365 + (wCurYear - 1921) / 4 + wCurDay + wMonthAdd[wCurMonth - 1] - 38;
if((!(wCurYear % 4)) && (wCurMonth > 2))
nTheDate = nTheDate + 1;
//计算农历天干、地支、月、日
nIsEnd = 0;
m = 0;
while(nIsEnd != 1)
{
if(wNongliData[m] < 4095)
k = 11;
else
k = 12;
n = k;
while(n>=0)
{
//获取wNongliData(m)的第n个二进制位的值
nBit = wNongliData[m];
for(i=1;i<n+1;i++)
nBit = nBit/2;
nBit = nBit % 2;
if (nTheDate <= (29 + nBit))
{
nIsEnd = 1;
break;
}
nTheDate = nTheDate - 29 - nBit;
n = n - 1;
}
if(nIsEnd)
break;
m = m + 1;
}
wCurYear = 1921 + m;
wCurMonth = k - n + 1;
wCurDay = nTheDate;
if (k == 12)
{
if (wCurMonth == wNongliData[m] / 65536 + 1)
wCurMonth = 1 - wCurMonth;
else if (wCurMonth > wNongliData[m] / 65536 + 1)
wCurMonth = wCurMonth - 1;
}
//生成农历天干、地支、属相
NSString *szShuXiang = (NSString *)[cShuXiang objectAtIndex:((wCurYear - 4) % 60) % 12];
//NSString *szNongli = [NSString stringWithFormat:@"%@(%@%@)年",szShuXiang, (NSString *)[cTianGan objectAtIndex:((wCurYear - 4) % 60) % 10],(NSString *)[cDiZhi objectAtIndex:((wCurYear - 4) % 60) % 12]];
//生成农历月、日
NSString *szNongliDay;
if (wCurMonth < 1){
szNongliDay = [NSString stringWithFormat:@"闰%@",(NSString *)[cMonName objectAtIndex:-1 * wCurMonth]];
}
else{
szNongliDay = (NSString *)[cMonName objectAtIndex:wCurMonth];
}
//NSString *lunarDate = [NSString stringWithFormat:@"%@ %@月 %@",szNongli,szNongliDay,(NSString *)[cDayName objectAtIndex:wCurDay]];
NSDictionary *nongliDic = @{@"shuxiang":szShuXiang,
@"nongliYear":[NSString stringWithFormat:@"%@%@",(NSString *)[cTianGan objectAtIndex:((wCurYear - 4) % 60) % 10],(NSString *)[cDiZhi objectAtIndex:((wCurYear - 4) % 60) % 12]],
@"month":szNongliDay,
@"day":[NSString stringWithFormat:@"%@",[cDayName objectAtIndex:wCurDay]]};
//
return nongliDic;
}
14,gif图播放。
//web url with gif
+ (CAKeyframeAnimation *)gifWithURL:(NSString *)url duration:(float)duration repeatCount:(float)repeatCount beginTime:(CFTimeInterval)beginTime atComplateRemove:(BOOL)remove
{
CGImageSourceRef cImageSource = [self CGImageSourceCreateWithURL:url];
size_t imageCount = CGImageSourceGetCount(cImageSource);
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *times = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *keyTimes = [[NSMutableArray alloc] initWithCapacity:imageCount];
CGFloat totalTime = 0;
for (size_t i = 0; i < imageCount; i++) {
CGImageRef cgimage= CGImageSourceCreateImageAtIndex(cImageSource, i, NULL);
[images addObject:(__bridge id)cgimage];
CGImageRelease(cgimage);
NSDictionary *properties = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(cImageSource, i, NULL);
NSDictionary *gifProperties = [properties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
NSString *gifDelayTime = [gifProperties valueForKey:(__bridge NSString* )kCGImagePropertyGIFDelayTime];
[times addObject:gifDelayTime];
totalTime += [gifDelayTime floatValue];
}
float currentTime = 0;
for (size_t i = 0; i < times.count; i++) {
float keyTime = currentTime / totalTime;
[keyTimes addObject:[NSNumber numberWithFloat:keyTime]];
currentTime += [[times objectAtIndex:i] floatValue];
}
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:StickerAnimationByContents];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[animation setValues:images];
[animation setKeyTimes:keyTimes];
animation.beginTime = beginTime;
animation.removedOnCompletion = remove;
animation.fillMode = kCAFillModeForwards;
animation.duration = duration;
//totalTime;
animation.repeatCount = repeatCount;
return animation;
}
+ (CGImageSourceRef)CGImageSourceCreateWithURL:(NSString *)url
{
NSData *gifData = [[YYImageCache sharedCache] getImageDataForKey:url];
CGImageSourceRef cImageSource = CGImageSourceCreateWithData((CFDataRef)gifData, NULL);
return cImageSource;
}
15,数据请求中,对URL进行转码,否则服务器找不到地址:
//格式化URL
+(NSString *)encodeUrl:(NSString *)sourceURL
{
if (System_Version_Later(9.0)) {
return [sourceURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}else{
return [sourceURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
}
}
16,循环请求数据,请求完主线程进行添加,请求为异步:
NSMutableArray<NSNumber *> *stars = [NSMutableArray array];
dispatch_group_t starRequestGroup = dispatch_group_create();
dispatch_queue_t searialQueue = dispatch_queue_create("com.santong.starRequestQueue", DISPATCH_QUEUE_SERIAL);
for (NSInteger i = 0; i < 4; i++) {
dispatch_group_enter(starRequestGroup);
dispatch_group_async(starRequestGroup, searialQueue, ^{
[self SL_MyInfoStarsParams:@{@"starId":@(i)} willRequestHandle:nil atComplateHandle:^(NSError * _Nonnull error, SLSuperModel * _Nonnull superModel) {
dispatch_group_leave(starRequestGroup);
if(error == nil && RequestSucceedCode == superModel.code){
[stars addObject:superModel.obj];
}else{
[stars addObject:@(0)];
}
}];
});
}
WeakSelf(weakSelf);
dispatch_group_notify(starRequestGroup, searialQueue, ^{
//分配
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.meCtrl.headerView setStarsWithArray:stars.copy];
});
});
17,UITextView加入html富文本之后计算其高度:
NSData *data = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *html = [[NSAttributedString alloc]initWithData:data
options:options
documentAttributes:nil
error:nil];
CGRect rect = [html boundingRectWithSize:CGSizeMake(ScreenWidth - ScaleForLengthWith2(24.0) * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingUsesDeviceMetrics context:nil];
CGFloat finalHeight = ceil(rect.size.height) + 8;
// NSLog(@"%@",NSStringFromCGRect(rect));
self.textView.attributedText = html;
18,AutoLayout自适应TableViewCell之后,获取整个TableView的ContentSize:
[weakSelf.listTableView layoutIfNeeded]; weakSelf.listTableView.frame = CGRectMake(0, 0, weakSelf.listTableView.width, msgTableView.contentSize.height); NSLog(@"contentSize = = = %lf",msgTableView.contentSize.height);
19,SDImageCache获取缓存图片
SDImageCache通过URL获取缓存图片: 1,通过URL获取当前项目缓存中的图片路径,返回NSString: [[SDImageCache sharedImageCache] defaultCachePathForKey:url]; 2,通过URL获取当前项目缓存中的图片,返回UIImage: [[SDImageCachesharedImageCache] imageFromDiskCacheForKey:url];
20,提取URL中的参数及参数值:
- (NSMutableDictionary *)parseURLParameters:(NSString *)url{
NSRange range = [url rangeOfString:@"?"];
if (range.location == NSNotFound) return nil;
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
NSString *parametersString = [url substringFromIndex:range.location + 1];
if ([parametersString containsString:@"&"]) {
NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
for (NSString *keyValuePair in urlComponents) {
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
if (key == nil || value == nil) {
continue;
}
id existValue = [parameters valueForKey:key];
if (existValue != nil) {
if ([existValue isKindOfClass:[NSArray class]]) {
NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
[items addObject:value];
[parameters setValue:items forKey:key];
} else {
[parameters setValue:@[existValue, value] forKey:key];
}
} else {
[parameters setValue:value forKey:key];
}
}
} else {
NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
if (pairComponents.count == 1) {
return nil;
}
NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
if (key == nil || value == nil) {
return nil;
}
[parameters setValue:value forKey:key];
}
return parameters;
}

