iOS之Reachability检测网络状态

  1. 首先 下载Reachability.zip

  2. 解压之后将Reachability.hReachability.m文件拖入自己的项目中

  3. AppDelegate.m中引入Reachability.h

  4. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions NS_AVAILABLE_IOS(3_0);方法里添加观察者监听网络状态改变的通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 监听网络状态改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    // 创建Reachability
    Reachability *connect = [Reachability reachabilityForInternetConnection];
    // 开始监控网络,若网络状态改变, 就会发出通知kReachabilityChangedNotification
    [connect startNotifier];
    return YES;
  }




// 处理网络状态改变
- (void)networkStateChange
{
    
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reachability currentReachabilityStatus]) {
        case 0://没有网
            [[[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        case 1:
            NSLog(@"WIFI网络");
            break;
        case 2:
            NSLog(@"手机自带网络");
            break;
        default:
            break;
    }
}

你可能感兴趣的:(iOS之Reachability检测网络状态)