iOS 常用公共方法

1. 獲取磁盤總空間大小或可用空間大小

//磁盤總空間

+ (CGFloat)diskOfAllSizeMBytes{

? ? ? ? ? ? CGFloatsize =0.0;

? ? ? ? ? ? NSError*error;

? ? ? ? ? ?NSDictionary*dic = [[NSFileManagerdefaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

? ? ? ? ? ?if(error) {?

? ? ? ? ? ? #ifdef DEBUG

? ? ? ? ? ? ?NSLog(@"error: %@", error.localizedDescription);

? ? ? ? ? ? #endif

? ? ? ? ? ? ? ?}else{

? ? ? ? ? ? ? ? NSNumber*number = [dic objectForKey:NSFileSystemSize];? ? ? //獲取總空間大小

? ? ? ? ? ? ? ? //NSNumber*number = [dic objectForKey:NSFileSystemFreeSize]; //獲取可用空間大小?

? ? ? ? ? ? ? ? size = [number floatValue]/1024/1024;? ? }

returnsize;

}

2. 獲取指定路徑下某個文件的大小

+ (longlong)fileSizeAtPath:(NSString *)filePath{ ? ?

NSFileManager *fileManager = [NSFileManager defaultManager];

if(![fileManagerfileExistsAtPath:filePath]){

return0 ;

? ? }else{

return[[fileManagerattributesOfItemAtPath:filePatherror:nil] fileSize];

? ?}

}

3. 獲取文件夾下所有文件的大小

+ (longlong)folderSizeAtPath:(NSString*)folderPath{

NSFileManager*fileManager = [NSFileManagerdefaultManager];

? ? ? ? if(![fileManager fileExistsAtPath:folderPath]){

? ? ? ? ?return 0:

? ? ? ? }else{

? ? ? ? ?NSEnumerator*filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];

? ? ? ? ? NSString*fileName;

? ? ? ? ?longlongfolerSize =0;

? ? ? ? ? ?while((fileName = [filesEnumerator nextObject]) !=nil) {

? ? ? ? ? ? ? NSString*filePath = [folderPath stringByAppendingPathComponent:fileName];? ? ? ??

? ? ? ? ? ? ? folerSize += [selffileSizeAtPath:filePath];? ?

? ? ? ? ? ? ? ?}

? ? ? ? ? ? ?returnfolerSize;?

? ?}

}

4.獲取字符串(或漢字)首字母

+ (NSString*)firstCharacterWithString:(NSString*)string{

NSMutableString*str = [NSMutableStringstringWithString:string];

CFStringTransform((CFMutableStringRef)str,NULL,kCFStringTransformMandarinLatin,NO);

CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);

NSString*pingyin = [str capitalizedString];

return[pingyin substringToIndex:1];

}

5. 將字符串數組按照元素首字母順序進行排序分組


+ (NSDictionary*)dictionaryOrderByCharacterWithOriginalArray:(NSArray*)array{

? ? ?if(array.count ==0) {returnnil;}

? ? ? for(id ?obj ?in array) {

? ? ? ? ? ? ? ? ?if(![obj isKindOfClass:[NSStringclass]]) ?{ ?

? ? ? ? ? ? ? ? ? ?returnnil; ? ? ?

? ? ? ? ? ? ? ? } ? ?

? ? }

? ? UILocalizedIndexedCollation*indexedCollation = [UILocalizedIndexedCollationcurrentCollation];

? ? ? NSMutableArray*objects = [NSMutableArrayarrayWithCapacity:indexedCollation.sectionTitles.count];

? ? ? ?//創建27個分組數組

? ? ? ? for(inti =0; i < indexedCollation.sectionTitles.count; i++) {

? ? ? ? ? ? ? ?NSMutableArray*obj = [NSMutableArrayarray];? ? ? ?

? ? ? ? ? ? ? ? [objects addObject:obj];? ??

? ? ? ? ? ?}

? ? ? ?NSMutableArray*keys = [NSMutableArrayarrayWithCapacity:objects.count];

? ? ? ? //按字母順序進行分組

? ? ? ?NSInteger ? lastIndex =-1;

? ? ? ? ? for(inti =0; i < array.count; i++) {

? ? ? ? ? ? ? ? ? ?NSIntegerindex = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];? ? ? ?

? ? ? ? ? ? ? ? ? ?[[objects objectAtIndex:index] addObject:array[i]]; ? ? ? ?

? ? ? ? ? ? ? ? ? lastIndex = index;? ??

? ? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ? ? ? //去掉空數組

? ? ? ? ? ? ? ? ? for(inti =0; i < objects.count; i++) {

? ? ? ? ? ? ? ? ? ?NSMutableArray*obj = objects[i];

? ? ? ? ? ? ? ? ? ? ?if(obj.count ==0) {? ? ? ? ? ?

? ? ? ? ? ? ? ? ? ? [objects removeObject:obj]; ? ? ? ?

? ? ? ? ? ? ? ?}? ??

? ? ? ? ? ? }

? ? ? ? ? ? ? ? ?//獲取索引字母

? ? ? ? ? ? ? ?for(NSMutableArray*objinobjects) {

? ? ? ? ? ? ? ? NSString*str = obj[0];

? ? ? ? ? ? ? ? NSString*key = [selffirstCharacterWithString:str];? ? ? ?

? ? ? ? ? ? ? ? ?[keys addObject:key];? ??

? ? ? ? ? ? ? ? ? ?}

? ? ? ? ? ? ? ?NSMutableDictionary*dic = [NSMutableDictionarydictionary];? ?

? ? ? ? ? ? ? ?[dic setObject:objects forKey:keys];

? ? ? ? returndic;

?}

//獲取字符串(或漢字)首字母

+ (NSString*)firstCharacterWithString:(NSString*)string{

? ? NSMutableString*str = [NSMutableStringstringWithString: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= [UtilitiesdictionaryOrderByCharacterWithOriginalArray:arr];

NSLog(@"\n\ndic: %@",dic);

輸出結果如下:


輸出結果


6.獲取當前時間

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH時mm分ss秒"

+ (NSString*)currentDateWithFormat:(NSString*)format{

?NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];? ?

? [dateFormatter setDateFormat:format];

return[dateFormatter stringFromDate:[NSDatedate]];

}

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

? ? ? ? ? ? ? //時間間隔

? ? ? ? ? ? ? NSIntegerintevalTime = [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;

? ? ? ? ? ? NSIntegeryers = intevalTime /60/60/24/365;

? ? ? ? ? ? ? ? ? if(minutes <=10) {

? ? ? ? ? ? ? ? ? ? ? ?return@"剛剛";? ??

? ? ? ? ? ? ? ? ? ?}else if(minutes <60){

? ? ? ? ? ? ? ? ? ? return [NSStringstringWithFormat:@"%ld分鐘前",(long)minutes];? ??

? ? ? ? ? ? ? ? ? }else ?if(hours <24){

? ? ? ? ? ? ? ? ? ? return [NSStringstringWithFormat:@"%ld小時前",(long)hours];? ??

? ? ? ? ? ? ? ? ? }else if(day <30){

? ? ? ? ? ? ? ? ? ? return [NSStringstringWithFormat:@"%ld天前",(long)day];? ??

? ? ? ? ? ? ? ? ? ?}elseif(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: %@", [UtilitiestimeIntervalFromLastTime:@"2015年12月8日 15:50"lastTimeFormat:@"yyyy年MM月dd日 HH:mm"ToCurrentTime:@"2015/12/08 16:12"currentTimeFormat:@"yyyy/MM/dd HH:mm"]);

8. 判斷手機號碼格式是否正確

?+ (BOOL)valiMobile:(NSString*)mobile{? ??

? ? ? ? mobile = [mobile stringByReplacingOccurrencesOfString:@" "withString:@""];

? ? ? ? ? ?if(mobile.length !=11)? ??

? ? ? ? ? ?{returnNO;? ? }

? ? ? ? ? ?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 = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",CM_NUM];

? ? ? BOOLisMatch1 = [pred1 evaluateWithObject:mobile];

? ? ? ? NSPredicate*pred2 = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CU_NUM];

? ? ? ?BOOLisMatch2 = [pred2 evaluateWithObject:mobile];

? ? ? ?NSPredicate*pred3 = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",CT_NUM];

? ? ? BOOLisMatch3 = [pred3 evaluateWithObject:mobile];

? ? ? if(isMatch1 || isMatch2 || isMatch3) {returnYES;? ? ? ?

? ? ? ? }else{

? ? ? ? ? ? ? returnNO;? ? ? ?

? ? ? ? ?}? ??

? ? ? }

}

9.判斷郵箱格式是否正確

+ (BOOL)isAvailableEmail:(NSString*)email {

? ? ? ? NSString*emailRegex =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

? ? ? ?NSPredicate*emailTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];

? ? ? ?return[emailTest evaluateWithObject:email];

}

10. 將十六進制顏色轉換為 UIColor 對象

+ (UIColor *)colorWithHexString:(NSString *)color{

NSString *cString = [[colorstringByTrimmingCharactersInSet:[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 = [cStringsubstringFromIndex:2];

?}? if([cString hasPrefix:@"#"])?{

cString = [cStringsubstringFromIndex: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;

[[NSScannerscannerWithString:rString]scanHexInt:&r];

[[NSScannerscannerWithString:gString]scanHexInt:&g];

[[NSScannerscannerWithString:bString]scanHexInt:&b];

return[UIColorcolorWithRed:((float) r/ 255.0f) green:((float) g /255.0f)blue:((float) b /255.0f)alpha:1.0f];

}

11.創建一張實時模糊效果 View (毛玻璃效果)

//Avilable in iOS 8.0 and later

+ (UIVisualEffectView*)effectViewWithFrame:(CGRect)frame{

?UIBlurEffect*effect = [UIBlurEffecteffectWithStyle:UIBlurEffectStyleLight];

?UIVisualEffectView*effectView = [[UIVisualEffectView alloc] initWithEffect:effect];? ??

effectView.frame = frame;

?return effectView;

}

12. 截取一張 view 生成圖片

+ (UIImage*)shotWithView:(UIView*)view{

? ? UIGraphicsBeginImageContext(view.bounds.size); ??

?[view.layer renderInContext:UIGraphicsGetCurrentContext()];

?UIImage*image =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returnimage;

}

13. 截取view中某個區域生成一張圖片

+ (UIImage*)shotWithView:(UIView*)view scope:(CGRect)scope{

?CGImageRefimageRef=CGImageCreateWithImageInRect([selfshotWithView:view].CGImage,scope);

UIGraphicsBeginImageContext(scope.size);

CGContextRefcontext =UIGraphicsGetCurrentContext();

CGRectrect =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);

returnimage;

}

14. 壓縮圖片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)imagetoSize:(CGSize)size{ ? ?

?UIImage *resultImage =image;? ??

UIGraphicsBeginImageContext(size);? ??

[resultImage drawInRect:CGRectMake(0,0,size.width,size.height)];? ?

?UIGraphicsEndImageContext();

return resultImage;

}

15.壓縮圖片到指定文件大小

+ (NSData*)compressOriginalImage:(UIImage*)image toMaxDataSizeKBytes:(CGFloat)size{

NSData*data =UIImageJPEGRepresentation(image,1.0);

CGFloatdataKBytes = data.length/1000.0;

CGFloatmaxQuality =0.9f;CGFloatlastData = 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;? ? ? ?

? ?} ? ??

?}

returndata;

}

15. 獲取設備 IP 地址

需要先引入下頭文件:

#import <idaddrs.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(((structsockaddr_in*)temp_addr->ifa_addr)->sin_addr)];? ? ? ? ? ? ? ??

? ? ? ? ? ? ? ? ?}? ? ? ? ? ??

? ? ? ? ?}? ? ? ? ? ??

? ? ? temp_addr = temp_addr->ifa_next;? ? ? ?

? ? ? ? ?}? ??

? ? ?}? ??

? ? freeifaddrs(interfaces);

? ?returnaddress;

}


16. 判斷字符串中是否含有空格

+ (BOOL)isHaveSpaceInString:(NSString*)string{

?NSRange_range = [string rangeOfString:@" "];

? ?if(_range.location !=NSNotFound) {

? ? ?return YES;? ?

? ? ?}else{

? ?return NO; ? ??

? ? ?}

}

17.判斷字符串中是否含有某個字符串

+ (BOOL)isHaveString:(NSString*)string1 InString:(NSString*)string2{

? ? ? ?NSRange_range = [string2 rangeOfString:string1];

? ? ? if(_range.location !=NSNotFound) {

? ? ? ? return YES;? ?

? ? ? ?}else{

? ? ? ?return NO;? ??

? ? ? }

}

18.判斷字符串中是否含有中文

+ (BOOL)isHaveChineseInString:(NSString*)string{

? ? ? ? ? for(NSIntegeri =0; i < [string length]; i++){

? ? ? ? ? ? int ? a = [string characterAtIndex:i];

? ? ? ? ? ? ?if(a >0x4e00 && a <0x9fff) {

? ? ? ? ? ? ? ? ?return YES;? ? ? ??

? ? ? ? ? ? ?}? ??

? ? ? ?}

return NO;

}

19.判斷字符串是否全部為數字

+ (BOOL)isAllNum:(NSString*)string{

?unichar c

?;for(inti=0; i<string.length ; i++) {

c=[string characterAtIndex:i];

if(!isdigit(c)) {

? ? ? ? ?return NO;? ? ? ??

? ? }

} return YES;}



20.將字典對象轉換為 JSON 字符串

+ (NSString*)jsonPrettyStringEncoded:(NSArray*)array{

if([NSJSONSerializationisValidJSONObject:array]) {

NSError*error;

NSData*jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrintederror:&error];

if(!error) {

? ? ? ? NSString*json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

? ? ? ? returnjson;? ? ? ??

? ?}? ?

?}

returnnil;

}

21. 獲取 WiFi 信息

引入頭文件#import <SystemConfiguration/CaptiveNetwork.h>

代碼:

- (NSDictionary*)fetchSSIDInfo {

?NSArray*ifs = (__bridge_transfer NSArray*)CNCopySupportedInterfaces();

? ?if(!ifs) {

? ? ? return nil;? ??

? }

NSDictionary*info =nil;

?for(NSString*ifnam ? ?in ? ifs) {? ? ? ??

? ? ? info = (__bridge_transferNSDictionary*)CNCopyCurrentNetworkInfo((__bridgeCFStringRef)ifnam);

? ? ? ?if(info && [info count]) {

? ? ? ? break;?

? ? ? }? ??

? ?}

returninfo;

}

30. 獲取廣播地址、本機地址、子網掩碼、端口信息

需要引入頭文件:

#import? <ifaddrs.h>

#import <arpa/inet.h>

//獲取廣播地址、本機地址、子網掩碼、端口信息

- (NSMutableDictionary *)getLocalInfoForCurrentWiFi {? ?

?NSMutableDictionary *dict = [NSMutableDictionary dictionary];

structifaddrs*interfaces = NULL;

structifaddrs*temp_addr = NULL;

intsuccess =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(((structsockaddr_in*)temp_addr->ifa_dstaddr)->sin_addr)];

? ? ? ? ? ? ?if(broadcast) {? ? ? ? ? ? ? ? ? ? ? ??

? ? ? ? ? ? ? ?[dict setObject:broadcast forKey:@"broadcast"];? ? ? ? ? ? ? ? ? ??

? ? ? ? ? ? }//? ? ? ? ? ? ? ? ? ? NSLog(@"broadcast address--%@",broadcast);

? ? ? ? ? ? //本機地址

? ? ? ? ? ? NSString *localIp = [NSString stringWithUTF8String:inet_ntoa(((structsockaddr_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(((structsockaddr_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);returndict;? ? ? ? ? ? ? ??

? ? ? }? ? ? ? ? ??

? ? }? ? ? ? ? ?

? temp_addr = temp_addr->ifa_next;? ? ? ?

? ? ?}? ?

? ?}// Free memoryfreeifaddrs(interfaces);

returndict;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容