iOS--检测网络状态,获取运营商,获取WIFI信号强度

在APP中,有时候需要对用户设备的网络状态进行实时监控,让用户了解自己的网络状态,根据用户的网络状态进行智能处理,节省用户流量,提高用户体验.
检测网络状态有多重方法,最常见的是 苹果官方提供了一个叫Reachability和AFNetworing检测网络(网上很多二者的用法,自行百度).但是,细心的朋友们不知道有没有发现,手机的状态栏上一般都会有当前网络状态的显示,因为状态栏是系统级别的View,是受苹果保护的,不可以随便更改,不可以随便遮挡住。如果违反这些苹果的规范,那么APP将有可能上不了架。所以一般很少对状态栏操作,但是状态栏并非不能操作,下面演示下状态栏的简单用法.
一、操作状态栏的样式
ios开发中对状态栏的操作比较少,开发中最常见的对状态栏的操作就是设置状态栏的样式,比如:

 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

(此样式的状态栏中的字为白色,所以用在导航栏为深色的情况下,例如黑色或者红色的导航栏)

默认的状态栏样式是:

  [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

(此样式的状态栏中的字为黑色色,所以用在导航栏为浅色色的情况下,比如白色的导航栏)
如果你设置了,发现状态栏没反应,那么你要去info.plist中加一个key,这个key为View controller-based status bar appearance,对应的value为NO。这样每个vc中就可以随便设置状态栏的样式了。

View controller-based status bar appearance :NO

二、操作状态栏的背景颜色
我们可以拿到状态栏这个UIView对象,可以改变状态栏的颜色,背景颜色(backgroundColor)、大小位置(frame)等等。

1.png

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *bg = [self statusBarView];
    bg.backgroundColor = [UIColor redColor]; 
    bg.frame = CGRectMake(0, 100, self.view.frame.size.width, 60);
}

- (UIView*)statusBarView;
{
    UIView *statusBar = nil;
    NSData *data = [NSData dataWithBytes:(unsigned char []){0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0x61, 0x72} length:9];
    NSString *key = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    id object = [UIApplication sharedApplication];
    if ([object respondsToSelector:NSSelectorFromString(key)]) statusBar = [object valueForKey:key];
    return statusBar;
}

以上是状态栏的简单操作和设置,一般情况下也用不到,因为真是项目开发中不会这样随意改变状态栏的高度及颜色,但是状态栏上的这些信息一般都还是有用的.接着看代码

2.png

三、操作状态栏,得到网络类型
定义一个NetworkTools工具类,用来获取网络类型及状态,要知道最终获取到状态栏上的运营商名称要经过一层层的提取,下面就开始一层层分析

//1.状态栏是由当前app控制的,首先获取当前app
UIApplication *app = [UIApplication sharedApplication];
id statusBar = [app valueForKeyPath:@"statusBar"];
// 遍历状态栏的所有成员
unsigned int outCount =0;
Ivar *ivars = class_copyIvarList([statusBar class], &outCount);
for (int i =0; i < outCount; i++) {
    Ivar ivar = ivars[i];
    printf("%s\n",ivar_getName(ivar));
}

打印结果:

_statusBarServer
_inProcessProvider
_showsForeground
_backgroundView
_foregroundView
_doubleHeightLabel
_doubleHeightLabelContainer
_currentDoubleHeightText
_currentRawData
_interruptedAnimationCompositeViews
_newStyleBackgroundView
_newStyleForegroundView
_slidingStatusBar
_requestedStyle
_styleOverrides
_styleAttributes
_orientation
_hidden
_suppressesHiddenSideEffects
_foreground
_registered
_waitingOnCallbackAfterChangingStyleOverridesLocally
_suppressGlow
_translucentBackgroundAlpha
_showOnlyCenterItems
_foregroundViewShouldIgnoreStatusBarDataDuringAnimation
_localDataOverrides
_tintColor
_lastUsedBackgroundColor
_nextTintTransition
_overrideHeight
_disableRasterizationReasons
_persistentAnimationsEnabled
_simulatesLegacyAppearance
_serverUpdatesDisabled
_timeHidden
_homeItemsDisabled
_statusBarWindow
_styleDelegate
_dockDataProvider
__transitionCoordinator
_foregroundColor
_legibilityStyle
  1. 进入foregroundView元素并遍历其所有子元素
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
for (id child in children) {
    NSLog(@"%@", [child class]);
}

打印结果:

UIStatusBarSignalStrengthItemView
UIStatusBarServiceItemView
UIStatusBarDataNetworkItemView
UIStatusBarBatteryItemView
UIStatusBarBluetoothItemView
UIStatusBarIndicatorItemView
UIStatusBarTimeItemView
  1. 进入UIStatusBarServiceItemView/UIStatusBarDataNetworkItemView/UIStatusBarSignalStrengthItemView元素并遍历其所有子元素
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
for (id child in children) {
    if ([child isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")]) {
        unsigned int outCount =0;
        Ivar *ivars = class_copyIvarList([child class], &outCount);
        for (int i =0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            printf("%s\n",ivar_getName(ivar));
        }
    }
}

打印结果:

_serviceString
_crossfadeString
_crossfadeStep
_maxWidth
_serviceWidth
_crossfadeWidth
_contentType
_loopingNecessaryForString
_loopNowIfNecessary
_loopingNow
_letterSpacing
  1. 通过serviceString获取运营商名称
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    for (id child in children) {
    if ([child isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")]) {
            
            // 遍历当前状态栏的所有属性,找到关于状态栏的
            unsigned int outCount =0;
            Ivar *ivars = class_copyIvarList([child class], &outCount);
            for (int i =0; i < outCount; i++) {
                Ivar ivar = ivars[i];
                printf("%s\n",ivar_getName(ivar));
            }
            
            //1._serviceString
            id type = [child valueForKeyPath:@"serviceString"];
            NSLog(@"_serviceString: %@", type);

        }
        
 if ([child isKindOfClass:NSClassFromString(@"UIStatusBarBatteryItemView")]) {
            unsigned int outCount =0;
            Ivar *ivars = class_copyIvarList([child class], &outCount);
            for (int i =0; i < outCount; i++) {
                Ivar ivar = ivars[i];
                printf("%s\n",ivar_getName(ivar));
            }
            id cachedCapacity = [child valueForKeyPath:@"cachedCapacity"];
            NSLog(@"cachedCapacity: %@", cachedCapacity);
        }
        
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
   //获取网络类型
     NSInteger netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            NSLog(@"netType: %ld", netType);
    //wifi信号强度
            int signalStrength = [[child valueForKeyPath:@"wifiStrengthBars"]intValue];
            NSLog(@"netType: %d", signalStrength);
 }   
}

打印结果:

UIStatusBarDataNetworkItemView结果:
_dataNetworkType
_wifiStrengthRaw
_wifiStrengthBars
_wifiLinkWarning
_enableRSSI
_showRSSI

UIStatusBarBatteryItemView结果:
_capacity
_state
_batterySaverModeActive
_accessoryView
_cachedImageHasAccessoryImage
_cachedCapacity
_cachedImageSet
_cachedBatteryStyle

好了,至此我们已经拿到了网络状态,遍历UIStatusBar还可以获取到其他的有用信息,下面是一些常用的信息获取方式,封装了一个"NetworkTools"工具类

NetworkTools.h文件

//
//  NetworkTools.h
//  Demo
//
//  Created by Allison on 2017/7/13.
//  Copyright © 2017年 Allison. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NetworkTools : NSObject
// 获取设备uuid
+ (NSString*)getUUID;
// 设备mac 地址
+ (NSString *)macaddress;
// Version
+ (NSString *)getVersion;
// SIM卡所属的运营商(公司)
+(NSString *)serviceCompany;

+(NSDictionary *)getDinfo;


@end

NetworkTools.m文件

//
//  NetworkTools.m
//  Demo
//
//  Created by Allison on 2017/7/13.
//  Copyright © 2017年 Allison. All rights reserved.
//

#import "NetworkTools.h"
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>
#import <UIKit/UIKit.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <sys/stat.h> //真机必须导入这个头文件

/*
 * Top-level identifiers
 */
#define CTL_NET     4       /* network, see socket.h */
#define AF_ROUTE    17      /* Internal Routing Protocol */
#define AF_LINK     18      /* Link layer interface */
#define NET_RT_IFLIST2      6   /* interface list with addresses */
#define NET_RT_IFLIST       3   /* survey interface list */

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

//获取屏幕宽度
#define screenWide [UIScreen mainScreen].bounds.size.width
//获取屏幕高度
#define screenHeight [UIScreen mainScreen].bounds.size.height

@implementation NetworkTools

// 获取设备uuid
+ (NSString*)getUUID {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    return result;
}


// 设备mac 地址
+ (NSString *)macaddress
{
    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    NSLog(@"outString:%@", outstring);
    
    free(buf);
    
    return [outstring uppercaseString];
}

// Version
+ (NSString *)getVersion {
    
    NSString *string = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:string];
    NSString *version = [dic objectForKey:@"CFBundleVersion"];
    return version;
    
}
///SIM卡所属的运营商(公司)
+(NSString *)serviceCompany{
    NSArray *infoArray = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    for (id info in infoArray)
    {
        if ([info isKindOfClass:NSClassFromString(@"UIStatusBarServiceItemView")])
        {
            NSString *serviceString = [info valueForKeyPath:@"serviceString"];
            NSLog(@"公司为:%@",serviceString);
            return serviceString;
        }
    }
    return @"";
}


+ (NSDictionary *)getDinfo {
    NSString *mac = [self macaddress];
    NSString *udid = [self getUUID];
    NSString *ip = [self ipAddressIsV4:YES];
    NSString *p =  [self getDeviceInfo];
    NSString *jb = [NSString stringWithFormat:@"%i",[self jailbroken]];
    NSString *rw = [NSString stringWithFormat:@"%f",screenWide];
    NSString *rh = [NSString stringWithFormat:@"%f",screenHeight];
    NSString *o = [self chinaMobileModel];
    NSString *m = [self deviceName];
    NSString *osv = [self getSystemVersion];
    NSString *cv = [NSString stringWithFormat:@"%ld",[self version]];
    NSString *n = [self getNetWorkStates];
    
    NSDictionary *dinfo = @{
                            @"os":@"i",
                            @"osv": osv,
                            @"osvc":@"17",
                            @"udid": udid,
                            @"ip":ip,
                            @"p":p,
                            @"jb":jb,
                            @"rw":rw,
                            @"rh":rh,
                            @"o":o,
                            @"m":m,
                            @"cv":cv,
                            @"cvc":@"14",
                            @"mac": mac,
                            @"n":n,
                            @"phone":@"",
                            @"imsi":@"",
                            @"imei":@""
                            };
    return dinfo;
}

//  判断当前网络连接状态
+(NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];

    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            NSLog(@"netType:%d",netType);
            switch (netType) {
                case 0:
                    //                    state = @"无网络"; // 5
                    state = @"5";
                    //无网模式
                    break;
                case 1:
                    //                    state = @"2G"; // 1
                    state = @"1";
                    break;
                case 2:
                    //                    state = @"3G"; // 2
                    state = @"3";
                    break;
                case 3:
                    //                    state = @"4G"; //3
                    state = @"4";
                    break;
                case 5:
                    //                    state = @"WIFI"; //5
                    state = @"5";
                    break;
                default:
                    break;
            }
        }
    }
    //根据状态选择
    return state;
}


+ (NSString *)getSystemVersion {
    UIDevice *device = [[UIDevice alloc] init];
    NSString *systemVersion = device.systemVersion;
    return systemVersion;
}


// ip 地址
+ (NSString *)ipAddressIsV4:(BOOL)v4
{
    NSArray *searchArray = v4 ?
    @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self addressInfo];
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

// 设备信息 产品名称
+ (NSString *)getDeviceInfo {
    UIDevice *device = [[UIDevice alloc] init];
    NSString *name = device.name;       //获取设备所有者的名称
    NSString *model = device.name;      //获取设备的类别
    NSString *type = device.localizedModel; //获取本地化版本
    NSString *systemName = device.systemName;   //获取当前运行的系统
    NSString *systemVersion = device.systemVersion;//获取当前系统的版本
    NSLog(@"-----name : %@,model : %@,type : %@,systemName :%@,systemVersion %@",name,model,type,systemName,systemVersion);
    return model;
}

// 是否越狱
+ (BOOL)jailbroken
{
#if !TARGET_IPHONE_SIMULATOR
    
    //Apps and System check list
    BOOL isDirectory;
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Cyd", @"ia.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"bla", @"ckra1n.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Fake", @"Carrier.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Ic", @"y.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Inte", @"lliScreen.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"MxT", @"ube.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Roc", @"kApp.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"SBSet", @"ttings.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@", @"App", @"lic",@"ati", @"ons/", @"Wint", @"erBoard.a", @"pp"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/l", @"ib/a", @"pt/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/l", @"ib/c", @"ydia/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/mobile", @"Library/SBSettings", @"Themes/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/t", @"mp/cyd", @"ia.log"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"pr", @"iva",@"te/v", @"ar/s", @"tash/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/cy", @"dia/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"us", @"r/b",@"in", @"s", @"shd"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"us", @"r/sb",@"in", @"s", @"shd"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/cy", @"dia/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@", @"us", @"r/l",@"ibe", @"xe", @"c/sftp-", @"server"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@",@"/Syste",@"tem/Lib",@"rary/Lau",@"nchDae",@"mons/com.ike",@"y.bbot.plist"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@%@%@%@",@"/Sy",@"stem/Lib",@"rary/Laun",@"chDae",@"mons/com.saur",@"ik.Cy",@"@dia.Star",@"tup.plist"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/Libr",@"ary/Mo",@"bileSubstra",@"te/MobileSubs",@"trate.dylib"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/va",@"r/c",@"ach",@"e/a",@"pt/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"ib",@"/apt/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"ib/c",@"ydia/"] isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@", @"/va",@"r/l",@"og/s",@"yslog"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/bi",@"n/b",@"ash"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/b",@"in/",@"sh"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/et",@"c/a",@"pt/"]isDirectory:&isDirectory]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@", @"/etc/s",@"sh/s",@"shd_config"]]
        || [defaultManager fileExistsAtPath:[NSString stringWithFormat:@"/%@%@%@%@%@", @"/us",@"r/li",@"bexe",@"c/ssh-k",@"eysign"]])
        
    {
        return YES;
    }
    
    // SandBox Integrity Check
    int pid = fork(); //返回值:子进程返回0,父进程中返回子进程ID,出错则返回-1
    if(!pid){
        exit(0);
    }
    if(pid>=0)
    {
        return YES;
    }
    
    //Symbolic link verification
    struct stat s;
    if(lstat("/Applications", &s) || lstat("/var/stash/Library/Ringtones", &s) || lstat("/var/stash/Library/Wallpaper", &s)
       || lstat("/var/stash/usr/include", &s) || lstat("/var/stash/usr/libexec", &s)  || lstat("/var/stash/usr/share", &s)
       || lstat("/var/stash/usr/arm-apple-darwin9", &s))
    {
        if(s.st_mode & S_IFLNK){
            return YES;
        }
    }
    
    //Try to write file in private
    NSError *error;
    [[NSString stringWithFormat:@"Jailbreak test string"] writeToFile:@"/private/test_jb.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    if(nil==error){
        //Writed
        return YES;
    } else {
        [defaultManager removeItemAtPath:@"/private/test_jb.txt" error:nil];
    }
    
#endif
    return NO;
}


+ (NSDictionary *)addressInfo
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) || (interface->ifa_flags & IFF_LOOPBACK)) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                char addrBuf[INET6_ADDRSTRLEN];
                if(inet_ntop(addr->sin_family, &addr->sin_addr, addrBuf, sizeof(addrBuf))) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, addr->sin_family == AF_INET ? IP_ADDR_IPv4 : IP_ADDR_IPv6];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
    
}

// 运营商
+ (NSString *)chinaMobileModel
{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    if (carrier == nil) {
        //        return @"不识别";
        return @"0";
    }
    
    NSString *code = [carrier mobileNetworkCode];
    if (code == nil) {
        //        return @"不识别";
        return @"0";
    }
    
    if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"07"])
    {
        //        return @"移动";
        return @"1";
    }else if ([code isEqualToString:@"01"] || [code isEqualToString:@"06"])
    {
        //        return @"联通";
        return @"2";
    }else if ([code isEqualToString:@"03"] || [code isEqualToString:@"05"])
    {
        //        return @"电信";
        return @"3";
    }else if ([code isEqualToString:@"20"])
    {
        return @"铁通";
    }
    return @"不识别";
}

+ (NSString *)deviceModel
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *model = malloc(size);
    sysctlbyname("hw.machine", model, &size, NULL, 0);
    NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
    free(model);
    return deviceModel;
}


// 机型信息
+ (NSString *)deviceName
{
    NSString *platform = [self deviceModel];
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4 (GSM)";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5 (GSM)";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (CDMA)";
    if ([platform isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([platform isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini (GSM)";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3 (GSM)";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
    
    if ([platform isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([platform isEqualToString:@"iPad4,2"])      return @"iPad Air (GSM)";
    if ([platform isEqualToString:@"iPad4,3"])      return @"iPad Air (CDMA)";
    if ([platform isEqualToString:@"iPad4,4"])      return @"iPad Mini Retina (WiFi)";
    if ([platform isEqualToString:@"iPad4,5"])      return @"iPad Mini Retina (CDMA)";
    
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    return platform;
}
@end

用法:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *infoDic = [NetworkTools getDinfo];
    NSLog(@"%@", infoDic);
  }

输出结果

{
    cv = 0;
    cvc = 14;
    imei = "";
    imsi = "";
    ip = "192.168.0.110";
    jb = 0;
    m = "iPhone 6S";
    mac = "00:00:00:00:00:02";
    n = 5;
    o = 1;
    os = i;
    osv = "10.3.2";
    osvc = 17;
    p = "\U738b\U59e3\U59e3\U7684 iPhone";
    phone = "";
    rh = "568.000000";
    rw = "320.000000";
    udid = "AAAAAAAA-AAAA-AAAA-AAAA-D215092D9489";
}

最后附上下载地址:Demo.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容