1 //磁盘总空间 2 + (CGFloat)diskOfAllSizeMBytes{ 3 CGFloat size = 0.0; 4 NSError *error; 5 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; 6 if (error) { 7 #ifdef DEBUG 8 NSLog(@"error: %@", error.localizedDescription); 9 #endif 10 }else{ 11 NSNumber *number = [dic objectForKey:NSFileSystemSize]; 12 size = [number floatValue]/1024/1024; 13 } 14 return size; 15 }
1 //磁盘可用空间 2 + (CGFloat)diskOfFreeSizeMBytes{ 3 CGFloat size = 0.0; 4 NSError *error; 5 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; 6 if (error) { 7 #ifdef DEBUG 8 NSLog(@"error: %@", error.localizedDescription); 9 #endif 10 }else{ 11 NSNumber *number = [dic objectForKey:NSFileSystemFreeSize]; 12 size = [number floatValue]/1024/1024; 13 } 14 return size; 15 }
1 //获取文件大小 2 + (long long)fileSizeAtPath:(NSString *)filePath{ 3 NSFileManager *fileManager = [NSFileManager defaultManager]; 4 if (![fileManager fileExistsAtPath:filePath]) return 0; 5 return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; 6 }
1 //获取文件夹下所有文件的大小 2 + (long long)folderSizeAtPath:(NSString *)folderPath{ 3 NSFileManager *fileManager = [NSFileManager defaultManager]; 4 if (![fileManager fileExistsAtPath:folderPath]) return 0; 5 NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator]; 6 NSString *fileName; 7 long long folerSize = 0; 8 while ((fileName = [filesEnumerator nextObject]) != nil) { 9 NSString *filePath = [folderPath stringByAppendingPathComponent:fileName]; 10 folerSize += [self fileSizeAtPath:filePath]; 11 } 12 return folerSize; 13 }
1 //获取字符串(或汉字)首字母 2 + (NSString *)firstCharacterWithString:(NSString *)string{ 3 NSMutableString *str = [NSMutableString stringWithString:string]; 4 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); 5 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); 6 NSString *pingyin = [str capitalizedString]; 7 return [pingyin substringToIndex:1]; 8 }
1 //将字符串数组按照元素首字母顺序进行排序分组 2 + (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{ 3 if (array.count == 0) { 4 return nil; 5 } 6 for (id obj in array) { 7 if (![obj isKindOfClass:[NSString class]]) { 8 return nil; 9 } 10 } 11 UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation]; 12 NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count]; 13 //创建27个分组数组 14 for (int i = 0; i < indexedCollation.sectionTitles.count; i++) { 15 NSMutableArray *obj = [NSMutableArray array]; 16 [objects addObject:obj]; 17 } 18 NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count]; 19 //按字母顺序进行分组 20 NSInteger lastIndex = -1; 21 for (int i = 0; i < array.count; i++) { 22 NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)]; 23 [[objects objectAtIndex:index] addObject:array[i]]; 24 lastIndex = index; 25 } 26 //去掉空数组 27 for (int i = 0; i < objects.count; i++) { 28 NSMutableArray *obj = objects[i]; 29 if (obj.count == 0) { 30 [objects removeObject:obj]; 31 } 32 } 33 //获取索引字母 34 for (NSMutableArray *obj in objects) { 35 NSString *str = obj[0]; 36 NSString *key = [self firstCharacterWithString:str]; 37 [keys addObject:key]; 38 } 39 NSMutableDictionary *dic = [NSMutableDictionary dictionary]; 40 [dic setObject:objects forKey:keys]; 41 return dic; 42 } 43 44 //获取字符串(或汉字)首字母 45 + (NSString *)firstCharacterWithString:(NSString *)string{ 46 NSMutableString *str = [NSMutableString stringWithString:string]; 47 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO); 48 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO); 49 NSString *pingyin = [str capitalizedString]; 50 return [pingyin substringToIndex:1]; 51 }
使用如下:
NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];
NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];
NSLog(@"\n\ndic: %@", dic);
输出结果如下:
imageView2/2/w/1240" alt="" data-original-src="http://upload-images.jianshu.io/upload_images/1803339-a63d16ad6cccc312.png?imageMogr2/auto-orient/strip%7CimageView2/2">1 //获取当前时间 2 //format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒" 3 + (NSString *)currentDateWithFormat:(NSString *)format{ 4 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 5 [dateFormatter setDateFormat:format]; 6 return [dateFormatter stringFromDate:[NSDate date]]; 7 }
1 /** 2 * 计算上次日期距离现在多久 3 * 4 * @param lastTime 上次日期(需要和格式对应) 5 * @param format1 上次日期格式 6 * @param currentTime 最近日期(需要和格式对应) 7 * @param format2 最近日期格式 8 * 9 * @return xx分钟前、xx小时前、xx天前 10 */ 11 + (NSString *)timeIntervalFromLastTime:(NSString *)lastTime 12 lastTimeFormat:(NSString *)format1 13 ToCurrentTime:(NSString *)currentTime 14 currentTimeFormat:(NSString *)format2{ 15 //上次时间 16 NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init]; 17 dateFormatter1.dateFormat = format1; 18 NSDate *lastDate = [dateFormatter1 dateFromString:lastTime]; 19 //当前时间 20 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init]; 21 dateFormatter2.dateFormat = format2; 22 NSDate *currentDate = [dateFormatter2 dateFromString:currentTime]; 23 return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate]; 24 } 25 26 + (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{ 27 NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; 28 //上次时间 29 NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]]; 30 //当前时间 31 NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]]; 32 //时间间隔 33 NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate]; 34 35 //秒、分、小时、天、月、年 36 NSInteger minutes = intevalTime / 60; 37 NSInteger hours = intevalTime / 60 / 60; 38 NSInteger day = intevalTime / 60 / 60 / 24; 39 NSInteger month = intevalTime / 60 / 60 / 24 / 30; 40 NSInteger yers = intevalTime / 60 / 60 / 24 / 365; 41 42 if (minutes <= 10) { 43 return @"刚刚"; 44 }else if (minutes < 60){ 45 return [NSString stringWithFormat: @"%ld分钟前",(long)minutes]; 46 }else if (hours < 24){ 47 return [NSString stringWithFormat: @"%ld小时前",(long)hours]; 48 }else if (day < 30){ 49 return [NSString stringWithFormat: @"%ld天前",(long)day]; 50 }else if (month < 12){ 51 NSDateFormatter * df =[[NSDateFormatter alloc]init]; 52 df.dateFormat = @"M月d日"; 53 NSString * time = [df stringFromDate:lastDate]; 54 return time; 55 }else if (yers >= 1){ 56 NSDateFormatter * df =[[NSDateFormatter alloc]init]; 57 df.dateFormat = @"yyyy年M月d日"; 58 NSString * time = [df stringFromDate:lastDate]; 59 return time; 60 } 61 return @""; 62 }
使用如下:
NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50"
lastTimeFormat:@"yyyy年MM月dd日 HH:mm"
ToCurrentTime:@"2015/12/08 16:12"
currentTimeFormat:@"yyyy/MM/dd HH:mm"]);
输出结果如下:
1 //判断手机号码格式是否正确 2 + (BOOL)valiMobile:(NSString *)mobile{ 3 mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""]; 4 if (mobile.length != 11) 5 { 6 return NO; 7 }else{ 8 /** 9 * 移动号段正则表达式 10 */ 11 NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"; 12 /** 13 * 联通号段正则表达式 14 */ 15 NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"; 16 /** 17 * 电信号段正则表达式 18 */ 19 NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$"; 20 NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM]; 21 BOOL isMatch1 = [pred1 evaluateWithObject:mobile]; 22 NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM]; 23 BOOL isMatch2 = [pred2 evaluateWithObject:mobile]; 24 NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM]; 25 BOOL isMatch3 = [pred3 evaluateWithObject:mobile]; 26 27 if (isMatch1 || isMatch2 || isMatch3) { 28 return YES; 29 }else{ 30 return NO; 31 } 32 } 33 }
1 //利用正则表达式验证 2 + (BOOL)isAvailableEmail:(NSString *)email { 3 NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 4 NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 5 return [emailTest evaluateWithObject:email]; 6 }
1 //将十六进制颜色转换为 UIColor 对象 2 + (UIColor *)colorWithHexString:(NSString *)color{ 3 NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; 4 // String should be 6 or 8 characters 5 if ([cString length] < 6) { 6 return [UIColor clearColor]; 7 } 8 // strip "0X" or "#" if it appears 9 if ([cString hasPrefix:@"0X"]) 10 cString = [cString substringFromIndex:2]; 11 if ([cString hasPrefix:@"#"]) 12 cString = [cString substringFromIndex:1]; 13 if ([cString length] != 6) 14 return [UIColor clearColor]; 15 // Separate into r, g, b substrings 16 NSRange range; 17 range.location = 0; 18 range.length = 2; 19 //r 20 NSString *rString = [cString substringWithRange:range]; 21 //g 22 range.location = 2; 23 NSString *gString = [cString substringWithRange:range]; 24 //b 25 range.location = 4; 26 NSString *bString = [cString substringWithRange:range]; 27 // Scan values 28 unsigned int r, g, b; 29 [[NSScanner scannerWithString:rString] scanHexInt:&r]; 30 [[NSScanner scannerWithString:gString] scanHexInt:&g]; 31 [[NSScanner scannerWithString:bString] scanHexInt:&b]; 32 return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; 33 }
1 #pragma mark - 对图片进行滤镜处理 2 // 怀旧 --> CIPhotoEffectInstant 单色 --> CIPhotoEffectMono 3 // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade 4 // 色调 --> CIPhotoEffectTonal 冲印 --> CIPhotoEffectProcess 5 // 岁月 --> CIPhotoEffectTransfer 铬黄 --> CIPhotoEffectChrome 6 // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField 7 + (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{ 8 CIContext *context = [CIContext contextWithOptions:nil]; 9 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 10 CIFilter *filter = [CIFilter filterWithName:name]; 11 [filter setValue:inputImage forKey:kCIInputImageKey]; 12 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 13 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 14 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 15 CGImageRelease(cgImage); 16 return resultImage; 17 }
1 #pragma mark - 对图片进行模糊处理 2 // CIGaussianBlur ---> 高斯模糊 3 // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later) 4 // CIDiscBlur ---> 环形卷积模糊(Available in iOS 9.0 and later) 5 // CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later) 6 // CIMotionBlur ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later) 7 + (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{ 8 CIContext *context = [CIContext contextWithOptions:nil]; 9 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 10 CIFilter *filter; 11 if (name.length != 0) { 12 filter = [CIFilter filterWithName:name]; 13 [filter setValue:inputImage forKey:kCIInputImageKey]; 14 if (![name isEqualToString:@"CIMedianFilter"]) { 15 [filter setValue:@(radius) forKey:@"inputRadius"]; 16 } 17 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 18 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 19 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 20 CGImageRelease(cgImage); 21 return resultImage; 22 }else{ 23 return nil; 24 } 25 }
1 /** 2 * 调整图片饱和度, 亮度, 对比度 3 * 4 * @param image 目标图片 5 * @param saturation 饱和度 6 * @param brightness 亮度: -1.0 ~ 1.0 7 * @param contrast 对比度 8 * 9 */ 10 + (UIImage *)colorControlsWithOriginalImage:(UIImage *)image 11 saturation:(CGFloat)saturation 12 brightness:(CGFloat)brightness 13 contrast:(CGFloat)contrast{ 14 CIContext *context = [CIContext contextWithOptions:nil]; 15 CIImage *inputImage = [[CIImage alloc] initWithImage:image]; 16 CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"]; 17 [filter setValue:inputImage forKey:kCIInputImageKey]; 18 19 [filter setValue:@(saturation) forKey:@"inputSaturation"]; 20 [filter setValue:@(brightness) forKey:@"inputBrightness"]; 21 [filter setValue:@(contrast) forKey:@"inputContrast"]; 22 23 CIImage *result = [filter valueForKey:kCIOutputImageKey]; 24 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; 25 UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; 26 CGImageRelease(cgImage); 27 return resultImage; 28 }
1 //Avilable in iOS 8.0 and later 2 + (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{ 3 UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; 4 UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; 5 effectView.frame = frame; 6 return effectView; 7 }
1 //全屏截图 2 + (UIImage *)shotScreen{ 3 UIWindow *window = [UIApplication sharedApplication].keyWindow; 4 UIGraphicsBeginImageContext(window.bounds.size); 5 [window.layer renderInContext:UIGraphicsGetCurrentContext()]; 6 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 7 UIGraphicsEndImageContext(); 8 return image; 9 }
1 //截取view生成一张图片 2 + (UIImage *)shotWithView:(UIView *)view{ 3 UIGraphicsBeginImageContext(view.bounds.size); 4 [view.layer renderInContext:UIGraphicsGetCurrentContext()]; 5 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 6 UIGraphicsEndImageContext(); 7 return image; 8 }
1 //截取view中某个区域生成一张图片 2 + (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{ 3 CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope); 4 UIGraphicsBeginImageContext(scope.size); 5 CGContextRef context = UIGraphicsGetCurrentContext(); 6 CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height); 7 CGContextTranslateCTM(context, 0, rect.size.height);//下移 8 CGContextScaleCTM(context, 1.0f, -1.0f);//上翻 9 CGContextDrawImage(context, rect, imageRef); 10 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 11 UIGraphicsEndImageContext(); 12 CGImageRelease(imageRef); 13 CGContextRelease(context); 14 return image; 15 }
1 //压缩图片到指定尺寸大小 2 + (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{ 3 UIImage *resultImage = image; 4 UIGraphicsBeginImageContext(size); 5 [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; 6 UIGraphicsEndImageContext(); 7 return resultImage; 8 }
1 //压缩图片到指定文件大小 2 + (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{ 3 NSData *data = UIImageJPEGRepresentation(image, 1.0); 4 CGFloat dataKBytes = data.length/1000.0; 5 CGFloat maxQuality = 0.9f; 6 CGFloat lastData = dataKBytes; 7 while (dataKBytes > size && maxQuality > 0.01f) { 8 maxQuality = maxQuality - 0.01f; 9 data = UIImageJPEGRepresentation(image, maxQuality); 10 dataKBytes = data.length/1000.0; 11 if (lastData == dataKBytes) { 12 break; 13 }else{ 14 lastData = dataKBytes; 15 } 16 } 17 return data; 18 }
1 需要先引入下头文件: 2 3 #import <ifaddrs.h> 4 #import <arpa/inet.h> 5 代码: 6 7 //获取设备 IP 地址 8 + (NSString *)getIPAddress { 9 NSString *address = @"error"; 10 struct ifaddrs *interfaces = NULL; 11 struct ifaddrs *temp_addr = NULL; 12 int success = 0; 13 success = getifaddrs(&interfaces); 14 if (success == 0) { 15 temp_addr = interfaces; 16 while(temp_addr != NULL) { 17 if(temp_addr->ifa_addr->sa_family == AF_INET) { 18 if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { 19 address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; 20 } 21 } 22 temp_addr = temp_addr->ifa_next; 23 } 24 } 25 freeifaddrs(interfaces); 26 return address; 27 }
1 + (BOOL)isHaveSpaceInString:(NSString *)string{ 2 NSRange _range = [string rangeOfString:@" "]; 3 if (_range.location != NSNotFound) { 4 return YES; 5 }else { 6 return NO; 7 } 8 }
1 + (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{ 2 NSRange _range = [string2 rangeOfString:string1]; 3 if (_range.location != NSNotFound) { 4 return YES; 5 }else { 6 return NO; 7 } 8 }
1 + (BOOL)isHaveChineseInString:(NSString *)string{ 2 for(NSInteger i = 0; i < [string length]; i++){ 3 int a = [string characterAtIndex:i]; 4 if (a > 0x4e00 && a < 0x9fff) { 5 return YES; 6 } 7 } 8 return NO; 9 }
1 + (BOOL)isAllNum:(NSString *)string{ 2 unichar c; 3 for (int i=0; i<string.length; i++) { 4 c=[string characterAtIndex:i]; 5 if (!isdigit(c)) { 6 return NO; 7 } 8 } 9 return YES; 10 }
1 /* 2 ** lineFrame: 虚线的 frame 3 ** length: 虚线中短线的宽度 4 ** spacing: 虚线中短线之间的间距 5 ** color: 虚线中短线的颜色 6 */ 7 + (UIView *)createDashedLineWithFrame:(CGRect)lineFrame 8 lineLength:(int)length 9 lineSpacing:(int)spacing 10 lineColor:(UIColor *)color{ 11 UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame]; 12 dashedLine.backgroundColor = [UIColor clearColor]; 13 CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 14 [shapeLayer setBounds:dashedLine.bounds]; 15 [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))]; 16 [shapeLayer setFillColor:[UIColor clearColor].CGColor]; 17 [shapeLayer setStrokeColor:color.CGColor]; 18 [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)]; 19 [shapeLayer setLineJoin:kCALineJoinRound]; 20 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]]; 21 CGMutablePathRef path = CGPathCreateMutable(); 22 CGPathMoveToPoint(path, NULL, 0, 0); 23 CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0); 24 [shapeLayer setPath:path]; 25 CGPathRelease(path); 26 [dashedLine.layer addSublayer:shapeLayer]; 27 return dashedLine; 28 }
1 + (NSString *)jsonPrettyStringEncoded:(NSDictionary *)dictionary{ 2 if ([NSJSONSerialization isValidJSONObject:dictionary ]) { 3 NSError *error; 4 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; 5 if (!error) { 6 NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 7 return json; 8 } 9 } 10 return nil; 11 }
1 + (NSString *)jsonPrettyStringEncoded:(NSArray *)array{ 2 if ([NSJSONSerialization isValidJSONObject:array]) { 3 NSError *error; 4 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; 5 if (!error) { 6 NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 7 return json; 8 } 9 } 10 return nil; 11 }
1 需要引入头文件: 2 3 #import <SystemConfiguration/CaptiveNetwork.h> 4 代码: 5 6 //获取 WiFi 信息 7 - (NSDictionary *)fetchSSIDInfo { 8 NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces(); 9 if (!ifs) { 10 return nil; 11 } 12 NSDictionary *info = nil; 13 for (NSString *ifnam in ifs) { 14 info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam); 15 if (info && [info count]) { break; } 16 } 17 return info; 18 }
1 需要引入头文件: 2 3 p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #ff4647}span.s1 {font-variant-ligatures: no-common-ligatures; color: #eb905a}span.s2 {font-variant-ligatures: no-common-ligatures} 4 5 #import <ifaddrs.h> 6 #import <arpa/inet.h> 7 //获取广播地址、本机地址、子网掩码、端口信息 8 - (NSMutableDictionary *)getLocalInfoForCurrentWiFi { 9 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 10 struct ifaddrs *interfaces = NULL; 11 struct ifaddrs *temp_addr = NULL; 12 int success = 0; 13 // retrieve the current interfaces - returns 0 on success 14 success = getifaddrs(&interfaces); 15 if (success == 0) { 16 // Loop through linked list of interfaces 17 temp_addr = interfaces; 18 //*/ 19 while(temp_addr != NULL) { 20 if(temp_addr->ifa_addr->sa_family == AF_INET) { 21 // Check if interface is en0 which is the wifi connection on the iPhone 22 if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { 23 //广播地址 24 NSString *broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]; 25 if (broadcast) { 26 [dict setObject:broadcast forKey:@"broadcast"]; 27 } 28 // NSLog(@"broadcast address--%@",broadcast); 29 //本机地址 30 NSString *localIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; 31 if (localIp) { 32 [dict setObject:localIp forKey:@"localIp"]; 33 } 34 // NSLog(@"local device ip--%@",localIp); 35 //子网掩码地址 36 NSString *netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]; 37 if (netmask) { 38 [dict setObject:netmask forKey:@"netmask"]; 39 } 40 // NSLog(@"netmask--%@",netmask); 41 //--en0 端口地址 42 NSString *interface = [NSString stringWithUTF8String:temp_addr->ifa_name]; 43 if (interface) { 44 [dict setObject:interface forKey:@"interface"]; 45 } 46 // NSLog(@"interface--%@",interface); 47 return dict; 48 } 49 } 50 temp_addr = temp_addr->ifa_next; 51 } 52 } 53 // Free memory 54 freeifaddrs(interfaces); 55 return dict; 56 }