iOS开发 获取当前网络状态

1、通过监听手机的statusbar的状态还获取用户的网络状态。可以通过苹果的审核在Appstore上架。

typedef NS_ENUM(NSUInteger,NetWorkStates) {
    NetworkStatesNone, // 没有网络
    NetworkStates2G, // 2G
    NetworkStates3G, // 3G
    NetworkStates4G, // 4G
    NetworkStatesWIFI // WIFI
};
+ (NetWorkStates)getNetWorkState {
    NSArray *subViews = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    NetWorkStates state = NetworkStatesNone;
    for (id child in subViews) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            NSInteger netWorkType = [[child valueForKeyPath:@"dataNetworkType"] integerValue];
            switch (netWorkType) {
                case 0:
                    state = NetworkStatesNone;
                    break;
                case 1:
                    state = NetworkStates2G;
                    break;
                case 2:
                    state = NetworkStates3G;
                    break;
                case 3:
                    state = NetworkStates4G;
                    break;
                case 5:
                    state = NetworkStatesWIFI;
                    break;
                default:
                    break;
            }
        }
    }
    return state;
}

2、通过Reachablity监听网络状态 对用户设备的网络状态进行实时监控。

- (void)checkNetworkStates
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange) name:kReachabilityChangedNotification object:nil];
    _reacha = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    [_reacha startNotifier];
}
- (void)networkChange {
    NetworkStatus status = [_reacha currentReachabilityStatus];
    
    switch (status) {
        case NotReachable:
            break;
        case ReachableViaWWAN:
            break;
        case ReachableViaWiFi:
            break;
        default:
            break;
    }
}

NewWorkStatus有三种状态:

typedef NS_ENUM(NSInteger, NetworkStatus) {
    // Apple NetworkStatus Compatible Names.
    NotReachable = 0,  //没有网络
    ReachableViaWiFi = 2, //wifi
    ReachableViaWWAN = 1 //运营商网络
};

你可能感兴趣的:(iOS开发 获取当前网络状态)