我们在代码编程中,经常用到各种小方法
下面是一些总结:(不定时增加)
16进制设置颜色
- (instancetype)colorFromHexString:(NSString *)hexString Alpha:(CGFloat)alpha
{
unsigned rgbValue = 0;
hexString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&rgbValue];
return [[self class] colorWithR:((rgbValue & 0xFF0000) >> 16) G:((rgbValue & 0xFF00) >> 8) B:(rgbValue & 0xFF) A:alpha];
}
//根据返回的16进制数据直接加“#”赋值 (有没有@“#”不会影响数值)
- (instancetype)colorFromHexString:(NSString *)hexString
{
return [self colorFromHexString:hexString Alpha:1.0];
}
设置文本显示的长度,多余部分有。。。省略
-(NSString*)stringByTruncateWithLength:(NSInteger)length
{
if( self.length > length )
{
NSMutableString *mstr = [NSMutableString stringWithString:self];
[mstr deleteCharactersInRange:NSMakeRange(length-3, mstr.length-length+3)];//设置显示文本长度
[mstr appendString:@"..."];
return mstr;
}
else
return self;
}
网络状态的监控
-(BOOL)networkAvailable
{
//创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
//获得连接的标志
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
return NO;
}
//根据获得的连接标志进行判断
// SCNetworkReachabilityFlags:保存返回的测试连接状态
// 其中常用的状态有:
// kSCNetworkReachabilityFlagsReachable:能够连接网络
// kSCNetworkReachabilityFlagsConnectionRequired:能够连接网络,但是首先得建立连接过程
// kSCNetworkReachabilityFlagsIsWWAN:判断是否通过蜂窝网覆盖的连接,比如EDGE,GPRS或者目前的3G.主要是区别通过WiFi的连接
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}
#MD5方法加密
-(NSString*)md5WithString:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
return [[NSString stringWithFormat:@"XXXXXXXXXXXXXXXX",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] lowercaseString];
}
获取本机IP地址
-(NSString*)localIP
{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
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;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
几种字符串格式的校验
手机号码校验
-(BOOL)validatePhoneNumber:(NSString*)phoneNumber
{
if ( phoneNumber.length == 0 || phoneNumber.length != 11 ) return NO;
NSString *regex = @"^((13[0-9])|(147)|(145)|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [pred evaluateWithObject:phoneNumber];
if (!isMatch) {
return NO;
}
return YES;
}
英文字符和数字混编校验(常用作密码校验)
-(BOOL)validatePassword:(NSString*)password
{
if (password.length<8>16)
{
return NO ;
}
BOOL numberResult = NO;
BOOL letterResult = NO;
for (int i = 0; i<password xss=removed>=48 && character <= 57 ) && numberResult == NO)
{
numberResult = YES;
}
// A~Z a~z
if (((character >=65 && character <=90) || (character >=97 && character <=122)) && letterResult == NO)
{
letterResult = YES;
}
if (numberResult == YES && letterResult ==YES)
{
return YES;
}
}
return NO;
}
邮箱校验
+(BOOL)validateEmailAddress:(NSString*)emailAddress
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
return [emailTest evaluateWithObject:emailAddress];
}
POST上传多个文件
//post上传数据
-(void)sendPostRequestWithFileToURL:(NSString*)apiName parameters:(NSDictionary*)params filePathName:(NSArray *)filePathName paramterName:(NSArray *)names mimeType:(NSArray *)mimeType
{
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = 10.f;
NSString *apiUrl = [self urlStringWithAPI:apiName];
NSDictionary *finalParams = [self dictionaryByAddingCommonParameters:params];
AFHTTPRequestOperation *operation = [manager POST:apiUrl parameters:finalParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for(int i = 0;i<filePathName.count;i++)
{
NSData *data = [NSData dataWithContentsOfFile:filePathName[i]];
[formData appendPartWithFileData:data name:names[i] fileName:[filePathName[i] lastPathComponent] mimeType:mimeType[i]];
}
}
success:^(AFHTTPRequestOperation * operation ,id responseObject) {
failure:^(AFHTTPRequestOperation * operatioon,NSError * error) {
}
字典转化为JSON二进制数据流
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicc options:NSJSONWritingPrettyPrinted error:nil];
“未完待续”
时间: 2024-10-02 18:44:24