iOS常用的公共方法详解

1. 获取磁盘总空间大小

//磁盘总空间
+ (CGFloat)diskOfAllSizeMBytes{
 CGFloat size = 0.0;
 NSError *error;
 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
 if (error) {
#ifdef DEBUG
 NSLog(@"error: %@", error.localizedDescription);
#endif
 }else{
 NSNumber *number = [dic objectForKey:NSFileSystemSize];
 size = [number floatValue]/1024/1024;
 }
 return size;
}

2. 获取磁盘可用空间大小

//磁盘可用空间
+ (CGFloat)diskOfFreeSizeMBytes{
 CGFloat size = 0.0;
 NSError *error;
 NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
 if (error) {
#ifdef DEBUG
 NSLog(@"error: %@", error.localizedDescription);
#endif
 }else{
 NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
 size = [number floatValue]/1024/1024;
 }
 return size;
}

3. 获取指定路径下某个文件的大小

//获取文件大小
+ (long long)fileSizeAtPath:(NSString *)filePath{
 NSFileManager *fileManager = [NSFileManager defaultManager];
 if (![fileManager fileExistsAtPath:filePath]) return 0;
 return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
}

4. 获取文件夹下所有文件的大小

//获取文件夹下所有文件的大小
+ (long long)folderSizeAtPath:(NSString *)folderPath{
 NSFileManager *fileManager = [NSFileManager defaultManager];
 if (![fileManager fileExistsAtPath:folderPath]) return 0;
 NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
 NSString *fileName;
 long long folerSize = 0;
 while ((fileName = [filesEnumerator nextObject]) != nil) {
 NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
 folerSize += [self fileSizeAtPath:filePath];
 }
 return folerSize;
}

5. 获取字符串(或汉字)首字母

//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
 NSMutableString *str = [NSMutableString stringWithString:string];
 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
 NSString *pingyin = [str capitalizedString];
 return [pingyin substringToIndex:1];
}

6. 将字符串数组按照元素首字母顺序进行排序分组

//将字符串数组按照元素首字母顺序进行排序分组
+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
 if (array.count == 0) {
 return nil;
 }
 for (id obj in array) {
 if (![obj isKindOfClass:[NSString class]]) {
  return nil;
 }
 }
 UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
 NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
 //创建27个分组数组
 for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
 NSMutableArray *obj = [NSMutableArray array];
 [objects addObject:obj];
 }
 NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
 //按字母顺序进行分组
 NSInteger lastIndex = -1;
 for (int i = 0; i < array.count; i++) {
 NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
 [[objects objectAtIndex:index] addObject:array[i]];
 lastIndex = index;
 }
 //去掉空数组
 for (int i = 0; i < objects.count; i++) {
 NSMutableArray *obj = objects[i];
 if (obj.count == 0) {
  [objects removeObject:obj];
 }
 }
 //获取索引字母
 for (NSMutableArray *obj in objects) {
 NSString *str = obj[0];
 NSString *key = [self firstCharacterWithString:str];
 [keys addObject:key];
 }
 NSMutableDictionary *dic = [NSMutableDictionary dictionary];
 [dic setObject:objects forKey:keys];
 return dic;
}
//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
 NSMutableString *str = [NSMutableString stringWithString:string];
 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
 CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
 NSString *pingyin = [str capitalizedString];
 return [pingyin substringToIndex:1];
}

使用如下:

NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];
NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];
NSLog(@"\n\ndic: %@", dic);

输出结果如下:

输出结果

7. 获取当前时间

//获取当前时间
//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"
+ (NSString *)currentDateWithFormat:(NSString *)format{
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:format];
 return [dateFormatter stringFromDate:[NSDate date]];
}

8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等

/**
 * 计算上次日期距离现在多久
 *
 * @param lastTime 上次日期(需要和格式对应)
 * @param format1  上次日期格式
 * @param currentTime 最近日期(需要和格式对应)
 * @param format2  最近日期格式
 *
 * @return xx分钟前、xx小时前、xx天前
 */
+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime
      lastTimeFormat:(NSString *)format1
       ToCurrentTime:(NSString *)currentTime
      currentTimeFormat:(NSString *)format2{
 //上次时间
 NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
 dateFormatter1.dateFormat = format1;
 NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
 //当前时间
 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
 dateFormatter2.dateFormat = format2;
 NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
 return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
}
+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
 NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
 //上次时间
 NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
 //当前时间
 NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
 //时间间隔
 NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
 //秒、分、小时、天、月、年
 NSInteger minutes = intevalTime / 60;
 NSInteger hours = intevalTime / 60 / 60;
 NSInteger day = intevalTime / 60 / 60 / 24;
 NSInteger month = intevalTime / 60 / 60 / 24 / 30;
 NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
 if (minutes <= 10) {
  return @"刚刚";
 }else if (minutes < 60){
  return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
 }else if (hours < 24){
  return [NSString stringWithFormat: @"%ld小时前",(long)hours];
 }else if (day < 30){
  return [NSString stringWithFormat: @"%ld天前",(long)day];
 }else if (month < 12){
  NSDateFormatter * df =[[NSDateFormatter alloc]init];
  df.dateFormat = @"M月d日";
  NSString * time = [df stringFromDate:lastDate];
  return time;
 }else if (yers >= 1){
  NSDateFormatter * df =[[NSDateFormatter alloc]init];
  df.dateFormat = @"yyyy年M月d日";
  NSString * time = [df stringFromDate:lastDate];
  return time;
 }
 return @"";
}

使用如下:

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"]);

输出结果如下:

输出结果

9. 判断手机号码格式是否正确

//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile{
 mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
 if (mobile.length != 11)
 {
  return NO;
 }else{
  /**
   * 移动号段正则表达式
   */
  NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
  /**
   * 联通号段正则表达式
   */
  NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
  /**
   * 电信号段正则表达式
   */
  NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
  NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
  BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
  NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
  BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
  NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
  BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
  if (isMatch1 || isMatch2 || isMatch3) {
   return YES;
  }else{
   return NO;
  }
 }
}

10. 判断邮箱格式是否正确

//利用正则表达式验证
+ (BOOL)isAvailableEmail:(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];
}

11. 将十六进制颜色转换为 UIColor 对象

//将十六进制颜色转换为 UIColor 对象
+ (UIColor *)colorWithHexString:(NSString *)color{
 NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
 // String should be 6 or 8 characters
 if ([cString length] < 6) {
  return [UIColor clearColor];
 }
 // strip "0X" or "#" if it appears
 if ([cString hasPrefix:@"0X"])
  cString = [cString substringFromIndex:2];
 if ([cString hasPrefix:@"#"])
  cString = [cString substringFromIndex:1];
 if ([cString length] != 6)
  return [UIColor clearColor];
 // Separate into r, g, b substrings
 NSRange range;
 range.location = 0;
 range.length = 2;
 //r
 NSString *rString = [cString substringWithRange:range];
 //g
 range.location = 2;
 NSString *gString = [cString substringWithRange:range];
 //b
 range.location = 4;
 NSString *bString = [cString substringWithRange:range];
 // Scan values
 unsigned int r, g, b;
 [[NSScanner scannerWithString:rString] scanHexInt:&r];
 [[NSScanner scannerWithString:gString] scanHexInt:&g];
 [[NSScanner scannerWithString:bString] scanHexInt:&b];
 return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

12. 对图片进行滤镜处理

#pragma mark - 对图片进行滤镜处理
// 怀旧 --> CIPhotoEffectInstant       单色 --> CIPhotoEffectMono
// 黑白 --> CIPhotoEffectNoir       褪色 --> CIPhotoEffectFade
// 色调 --> CIPhotoEffectTonal       冲印 --> CIPhotoEffectProcess
// 岁月 --> CIPhotoEffectTransfer      铬黄 --> CIPhotoEffectChrome
// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{
 CIContext *context = [CIContext contextWithOptions:nil];
 CIImage *inputImage = [[CIImage alloc] initWithImage:image];
 CIFilter *filter = [CIFilter filterWithName:name];
 [filter setValue:inputImage forKey:kCIInputImageKey];
 CIImage *result = [filter valueForKey:kCIOutputImageKey];
 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
 UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
 CGImageRelease(cgImage);
 return resultImage;
}

13. 对图片进行模糊处理

#pragma mark - 对图片进行模糊处理
// CIGaussianBlur ---> 高斯模糊
// CIBoxBlur  ---> 均值模糊(Available in iOS 9.0 and later)
// CIDiscBlur  ---> 环形卷积模糊(Available in iOS 9.0 and later)
// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)
// CIMotionBlur ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)
+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{
 CIContext *context = [CIContext contextWithOptions:nil];
 CIImage *inputImage = [[CIImage alloc] initWithImage:image];
 CIFilter *filter;
 if (name.length != 0) {
  filter = [CIFilter filterWithName:name];
  [filter setValue:inputImage forKey:kCIInputImageKey];
  if (![name isEqualToString:@"CIMedianFilter"]) {
   [filter setValue:@(radius) forKey:@"inputRadius"];
  }
  CIImage *result = [filter valueForKey:kCIOutputImageKey];
  CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
  UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
  CGImageRelease(cgImage);
  return resultImage;
 }else{
  return nil;
 }
}

14. 调整图片饱和度、亮度、对比度

/**
 * 调整图片饱和度, 亮度, 对比度
 *
 * @param image  目标图片
 * @param saturation 饱和度
 * @param brightness 亮度: -1.0 ~ 1.0
 * @param contrast 对比度
 *
 */
+ (UIImage *)colorControlsWithOriginalImage:(UIImage *)image
         saturation:(CGFloat)saturation
         brightness:(CGFloat)brightness
         contrast:(CGFloat)contrast{
 CIContext *context = [CIContext contextWithOptions:nil];
 CIImage *inputImage = [[CIImage alloc] initWithImage:image];
 CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
 [filter setValue:inputImage forKey:kCIInputImageKey];
 [filter setValue:@(saturation) forKey:@"inputSaturation"];
 [filter setValue:@(brightness) forKey:@"inputBrightness"];
 [filter setValue:@(contrast) forKey:@"inputContrast"];
 CIImage *result = [filter valueForKey:kCIOutputImageKey];
 CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
 UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
 CGImageRelease(cgImage);
 return resultImage;
}

15. 创建一张实时模糊效果 View (毛玻璃效果)

//Avilable in iOS 8.0 and later
+ (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{
 UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
 UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
 effectView.frame = frame;
 return effectView;
}

16. 全屏截图

//全屏截图
+ (UIImage *)shotScreen{
 UIWindow *window = [UIApplication sharedApplication].keyWindow;
 UIGraphicsBeginImageContext(window.bounds.size);
 [window.layer renderInContext:UIGraphicsGetCurrentContext()];
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return image;
}

17. 截取一张 view 生成图片

//截取view生成一张图片
+ (UIImage *)shotWithView:(UIView *)view{
 UIGraphicsBeginImageContext(view.bounds.size);
 [view.layer renderInContext:UIGraphicsGetCurrentContext()];
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return image;
}

18. 截取view中某个区域生成一张图片

//截取view中某个区域生成一张图片

+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
 CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
 UIGraphicsBeginImageContext(scope.size);
 CGContextRef context = UIGraphicsGetCurrentContext();
 CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
 CGContextTranslateCTM(context, 0, rect.size.height);//下移
 CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
 CGContextDrawImage(context, rect, imageRef);
 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 CGImageRelease(imageRef);
 CGContextRelease(context);
 return image;
}

19. 压缩图片到指定尺寸大小

//压缩图片到指定尺寸大小
+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
 UIImage *resultImage = image;
 UIGraphicsBeginImageContext(size);
 [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
 UIGraphicsEndImageContext();
 return resultImage;
}

20. 压缩图片到指定文件大小

//压缩图片到指定文件大小
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
 NSData *data = UIImageJPEGRepresentation(image, 1.0);
 CGFloat dataKBytes = data.length/1000.0;
 CGFloat maxQuality = 0.9f;
 CGFloat lastData = dataKBytes;
 while (dataKBytes > size && maxQuality > 0.01f) {
  maxQuality = maxQuality - 0.01f;
  data = UIImageJPEGRepresentation(image, maxQuality);
  dataKBytes = data.length/1000.0;
  if (lastData == dataKBytes) {
   break;
  }else{
   lastData = dataKBytes;
  }
 }
 return data;
}

21. 获取设备 IP 地址

需要先引入下头文件:

#import <ifaddrs.h>
#import <arpa/inet.h>

代码:

//获取设备 IP 地址
+ (NSString *)getIPAddress {
 NSString *address = @"error";
 struct ifaddrs *interfaces = NULL;
 struct ifaddrs *temp_addr = NULL;
 int success = 0;
 success = getifaddrs(&interfaces);
 if (success == 0) {
  temp_addr = interfaces;
  while(temp_addr != NULL) {
   if(temp_addr->ifa_addr->sa_family == AF_INET) {
    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
     address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
    }
   }
   temp_addr = temp_addr->ifa_next;
  }
 }
 freeifaddrs(interfaces);
 return address;
}

22. 判断字符串中是否含有空格

+ (BOOL)isHaveSpaceInString:(NSString *)string{
 NSRange _range = [string rangeOfString:@" "];
 if (_range.location != NSNotFound) {
  return YES;
 }else {
  return NO;
 }
}

23. 判断字符串中是否含有某个字符串

+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{
 NSRange _range = [string2 rangeOfString:string1];
 if (_range.location != NSNotFound) {
  return YES;
 }else {
  return NO;
 }
}

24. 判断字符串中是否含有中文

+ (BOOL)isHaveChineseInString:(NSString *)string{
 for(NSInteger i = 0; i < [string length]; i++){
  int a = [string characterAtIndex:i];
  if (a > 0x4e00 && a < 0x9fff) {
   return YES;
  }
 }
 return NO;
}

25. 判断字符串是否全部为数字

+ (BOOL)isAllNum:(NSString *)string{
 unichar c;
 for (int i=0; i<string.length; i++) {
  c=[string characterAtIndex:i];
  if (!isdigit(c)) {
   return NO;
  }
 }
 return YES;
}

26. 绘制虚线

/*
 ** lineFrame:  虚线的 frame
 ** length:  虚线中短线的宽度
 ** spacing:  虚线中短线之间的间距
 ** color:   虚线中短线的颜色
*/
+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame
       lineLength:(int)length
       lineSpacing:(int)spacing
       lineColor:(UIColor *)color{
 UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];
 dashedLine.backgroundColor = [UIColor clearColor];
 CAShapeLayer *shapeLayer = [CAShapeLayer layer];
 [shapeLayer setBounds:dashedLine.bounds];
 [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];
 [shapeLayer setFillColor:[UIColor clearColor].CGColor];
 [shapeLayer setStrokeColor:color.CGColor];
 [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];
 [shapeLayer setLineJoin:kCALineJoinRound];
 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];
 CGMutablePathRef path = CGPathCreateMutable();
 CGPathMoveToPoint(path, NULL, 0, 0);
 CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);
 [shapeLayer setPath:path];
 CGPathRelease(path);
 [dashedLine.layer addSublayer:shapeLayer];
 return dashedLine;
}

27. 将字典对象转换为 JSON 字符串

+ (NSString *)jsonPrettyStringEncoded:(NSDictionary *)dictionary{
 if ([NSJSONSerialization isValidJSONObject:dictionary ]) {
  NSError *error;
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
  if (!error) {
   NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   return json;
  }
 }
 return nil;
}

28.将数组对象转换为 JSON 字符串

+ (NSString *)jsonPrettyStringEncoded:(NSArray *)array{
 if ([NSJSONSerialization isValidJSONObject:array]) {
  NSError *error;
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
  if (!error) {
   NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   return json;
  }
 }
 return nil;
}

29. 获取 WiFi 信息

需要引入头文件:

#import <SystemConfiguration/CaptiveNetwork.h>

代码:

//获取 WiFi 信息
- (NSDictionary *)fetchSSIDInfo {
 NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
 if (!ifs) {
  return nil;
 }
 NSDictionary *info = nil;
 for (NSString *ifnam in ifs) {
  info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
  if (info && [info count]) { break; }
 }
 return info;
}

30. 获取广播地址、本机地址、子网掩码、端口信息

需要引入头文件:

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}
#import <ifaddrs.h>
#import <arpa/inet.h>
//获取广播地址、本机地址、子网掩码、端口信息
- (NSMutableDictionary *)getLocalInfoForCurrentWiFi {
 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 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"]) {
     //广播地址
     NSString *broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
     if (broadcast) {
      [dict setObject:broadcast forKey:@"broadcast"];
     }
//     NSLog(@"broadcast address--%@",broadcast);
     //本机地址
     NSString *localIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
     if (localIp) {
      [dict setObject:localIp forKey:@"localIp"];
     }
//     NSLog(@"local device ip--%@",localIp);
     //子网掩码地址
     NSString *netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
     if (netmask) {
      [dict setObject:netmask forKey:@"netmask"];
     }
//     NSLog(@"netmask--%@",netmask);
     //--en0 端口地址
     NSString *interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
     if (interface) {
      [dict setObject:interface forKey:@"interface"];
     }
//     NSLog(@"interface--%@",interface);
     return dict;
    }
   }
   temp_addr = temp_addr->ifa_next;
  }
 }
 // Free memory
 freeifaddrs(interfaces);
 return dict;
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持我们!

(0)

相关推荐

  • iOS文字渐变色效果的实现方法

    照例先上文字渐变的效果图 实现思路如下 一.创建一个颜色渐变层,渐变图层跟文字控件一样大. 二.用文字图层裁剪渐变层,只保留文字部分,就会让渐变层只保留有文字的部分,相当于间接让渐变层显示文字,我们看到的其实是被裁剪过后,渐变层的部分内容. 注意:如果用文字图层裁剪渐变层,文字图层就不在拥有显示功能,这个图层就被弄来裁剪了,不会显示,在下面代码中也会有说明. 2.1 创建一个带有文字的label,label能显示文字. 2.2 设置渐变图层的mask为label图层,就能用文字裁剪渐变图层了.

  • IOS开发中键盘输入屏幕上移的解决方法

    在IOS开法中经常会遇到键盘遮挡屏幕的事情(比如输入账号密码验证码等等),就使得原本都不大的屏幕直接占了一半甚至更多的位置,这倒无所谓,关键是挡住了下面的按钮.这样的话按钮的事件也就触发不了,最好的解决办法就是当输入这些信息的时候让整个屏幕上移一个键盘的位置,或者上移到指定的位置. 首先一般输入的话都用的是UITextField,所以要监听用户什么时候开始输入和什么时候结束输入,直接设置代理代理就行了,要遵受 UITextFieldDelegate协议. //遵循协议 @interface Vi

  • iOS开发 全机型适配解决方法

    最近做项目,对于IPhone 手机机型适配很是头疼,所以整理下网上资料,记录下来,也许能帮助到正看文章的你, 今天打算跟大家聊聊最近研究的全机型适配思路. 当前我们需要适配的iPhone机型有4s.5s.6s.6Plus四种机型.它们的尺寸分别是 iphone4s {320, 480}                           960*640  iphone5 5s {320, 568}                       1136*640  iphone6 6s   {375

  • 详解优化iOS程序性能的25个方法

    1. 用ARC管理内存 ARC(Automatic ReferenceCounting, 自动引用计数)和iOS5一起发布,它避免了最常见的也就是经常是由于我们忘记释放内存所造成的内存泄露.它自动为你管理retain和release的过程,所以你就不必去手动干预了.忘掉代码段结尾的release简直像记得吃饭一样简单.而ARC会自动在底层为你做这些工作.除了帮你避免内存泄露,ARC还可以帮你提高性能,它能保证释放掉不再需要的对象的内存. 现在所有的iOS程序都用ARC了,这条可以忽略. 2. 在

  • iOS 防止按钮多次点击造成多次响应的方法

    iOS 防止按钮多次点击造成多次响应的方法 在日常开发中经常会碰到一种bug就是因为用户快速点击某个按钮,导致页面重复push或者重复发送网络请求.这样的问题既对用户体验有影响,而且还会一定程度上增加服务器的压力. 目前,我为了防止按钮快速点击主要使用以下两种办法 1.在每次点击时先取消之前的操作(网上看到的方法) - (void)buttonClicked:(id)sender { //这里是关键,点击按钮后先取消之前的操作,再进行需要进行的操作 [[self class] cancelPre

  • iOS拍照后图片自动旋转90度的完美解决方法

    今天开发一个拍照获取照片的功能的时候, 发现上传之后图片会自动旋转90. 测试发现, 只要是图片大于2M, 系统就会自动翻转照片 相机拍照后直接取出来的UIimage(用UIImagePickerControllerOriginalImage取出),它本身的imageOrientation属性是3,即UIImageOrientationRight.如果这个图片直接使用则没事,但是如果对它进行裁剪.缩放等操作后,它的这个imageOrientation属性会变成0.此时这张图片用在别的地方就会发生

  • iOS中生成指定大小、指定颜色的二维码和条形码方法详解

    iOS7.0之后可以利用系统原生 API 生成二维码, iOS8.0之后可以生成条形码, 系统默认生成的颜色是黑色. 在这里, 利用以下方法可以生成指定大小.指定颜色的二维码和条形码, 还可以添加背景颜色.阴影效果, 以下是具体方法. 一. 生成二维码 Avilable in iOS 7.0 and later 方法如下: #pragma mark - 生成二维码 //Avilable in iOS 7.0 and later + (UIImage *)qrCodeImageWithConten

  • iOS 四种回调方法总结

    最近对做IOS 项目遇到回调,抽空把相关资料整理下,以下是整理内容: 回调 回调就是将一段可执行的代码和一个特定的事件绑定起来.当特定的事件发生时,就会执行这段代码. 在Objective-C中,有四条途径可以实现回调. 目标-动作对 在程序开始定等待前,要求"当时间发生时,向指定的对象发送某个特定的信息".这里接收消息的对象是目标,消息的选择器是动作. 辅助对象 在程序开始等待之前,要求"当时间发生时,向遵守相应协议的辅助对象发送消息".委托对象和数据源是常见的辅

  • 详解IOS点击空白处隐藏键盘的几种方法介绍

    IOS7 点击空白处隐藏键盘的几种方法,具体如下: iOS开发中经常要用到输入框,默认情况下点击输入框就会弹出键盘,但是必须要实现输入框return的委托方法才能取消键盘的显示,对于用户体验来说很不友好,我们可以实现点击键盘以外的空白区域来将键盘隐藏,以下我总结出了几种隐藏键盘的方法: 首先说明两种可以让键盘隐藏的Method: 1.[view endEditing:YES]  这个方法可以让整个view取消第一响应者,从而让所有控件的键盘隐藏. 2.[textFiled resignFirst

  • iOS点击推送消息跳到应用指定页面方法

    现在的推送用的越来越频繁,几乎每个应用都开始用到了.其实又有几个用户会去看推送消息呢?没办法,产品经理最大啊,只是苦了我们这一帮程序员啊!闲话少说,进入正题.兄弟我用的是极光推送,自然是以极光推送为例了. 现在点击推送消息,有两种跳转方式:1.打开应用,跳转到应用首页:2.打开应用,跳转到指定页面. ​第一种,你什么都不用设置,只要注册极光应用就可以.这里就不写怎么注册极光应用了,可以参考官方文档,写的很详细. 第二种,重头戏来了. // APP未运行时获取通知的内容 remoteNotific

随机推荐