iOS 에서 자주 사용 하 는 공공 방법 에 대한 상세 한 설명

25913 단어 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(@"

dic: %@", 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(@"

result: %@", [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.16 진수 색상 을 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.실시 간 퍼 지 효과 보기(털 유리 효과)만 들 기

//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;
}
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

좋은 웹페이지 즐겨찾기