How to detect loss of internet reachability when wifi source loses connection?

后端 未结 3 1623
日久生厌
日久生厌 2021-02-04 16:10

I am trying hard to get the authentic internet connectivity status. I have used Apple\'s Reachability but it\'s only giving me the status of wifi connectivity i.e. not covering

相关标签:
3条回答
  • 2021-02-04 16:39

    According to Reachability it checks for not only wifi but also for WWAN/3G and no internet access, why do you think it does not check other than WIFI?

     typedef enum {
    
        NotReachable = 0,
    
        ReachableViaWiFi,
    
        ReachableViaWWAN
    
    } NetworkStatus;
    

    if you want to check the reachability to a particular host then you could set the host yourself like this

    Reachability *hostReach = [Reachability reachabilityWithHostName: @"www.google.com"];
    
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    
     switch (netStatus)
        {
            case ReachableViaWWAN:
            {
                NSLog(@"WWAN/3G");
                break;
            }
            case ReachableViaWiFi:
            {
                NSLog(@"WIFI");
                break;
            }
            case NotReachable:
            { 
                NSLog(@"NO Internet");
                break;
            }
    }
    
    0 讨论(0)
  • 2021-02-04 16:39

    See Jordan's Answer. There is a stupid bug in Apple's official Reachability.m. The type for returnValue should be "NetworkStatus" instead of "BOOL":

    - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
    {
        ...
        NetworkStatus returnValue = NotReachable;
        ...
    }
    

    Otherwise, you end up with the following terrible consequences:

    1. Even if cellular connection is available, it will be reported as unavailable.
    2. If Wifi is unavailable, Wifi will be reported as available if cellular connection is available.

    Can't believe Apple never bothered to fix this.

    (P.S. New to stack overflow and have no reps to upvote Jordan)

    0 讨论(0)
  • 2021-02-04 16:50

    I was getting too the Wifi flag even with it disconnected. There is a bug in the Reachability.m method:

    - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
    

    it uses a BOOL as return value, but it assigns to it the values of a struct with 3 values:

    typedef enum : NSInteger {
        NotReachable = 0,
        ReachableViaWiFi,
        ReachableViaWWAN
    } NetworkStatus;
    

    So if whether Wifi or Cellular are available, it will ReachableViaWiFi (as a BOOL can be 0 or 1, but not two)

    To fix it, just change in the method above this:

    BOOL returnValue = NotReachable;
    

    For this:

    int returnValue = NotReachable;
    

    And you're good to go. Hope it helps.

    0 讨论(0)
提交回复
热议问题