网络监听

作者: Vinch | 来源:发表于2017-07-04 09:09 被阅读7次

    网络监听

    1. AFNetworking自带

    -(void)startnetwork
    {
       AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
       [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
           // 当网络状态改变时调用
           switch (status) {
               case AFNetworkReachabilityStatusUnknown:
                   [self showHudTipStr:@"未知网络"];
                   break;
               case AFNetworkReachabilityStatusNotReachable:
               {
                   [self showHudTipStr:@"无网络连接"];
               }
                   break;
               case AFNetworkReachabilityStatusReachableViaWWAN:
                   [self showHudTipStr:@"已连接2G/3G/4G"];
                   [self autoUpdataToServer];
                   break;
               case AFNetworkReachabilityStatusReachableViaWiFi:
                   [self showHudTipStr:@"已连接WIFI"];
                   [self autoUpdataToServer];
                   break;
           }
       }];
       //开始监控
       [manager startMonitoring];
    }
    

    2. Reachability

    
    //开启网络状况的监听
       [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(reachabilityChanged:)
                                                    name: kReachabilityChangedNotification
                                                  object: nil];
       hostReach =[Reachability reachabilityWithHostName:@"wap.baidu.com"];//可以以多种形式初始化
       [hostReach startNotifier]; //开始监听,会启动一个run loop
    
    
    // 1.检测wifi状态
       Reachability *wifi = [Reachability reachabilityForLocalWiFi];
       // 2.检测手机是否能上网络(WIFI\3G\2.5G)
       Reachability *conn = [Reachability reachabilityForInternetConnection];
       // 3.判断网络状态
       if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
           return YES;
       } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
           return YES;
       } else { // 没有网络
           return NO;
       }
    
    

    相关文章

      网友评论

        本文标题:网络监听

        本文链接:https://www.haomeiwen.com/subject/osethxtx.html