Using Reachability for Internet *or* local WiFi?

前端 未结 4 485
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 00:37

I\'ve searched SO for the answer to this question, and it\'s not really addressed, at least not to a point where I can make it work.

I was originally only checking f

相关标签:
4条回答
  • 2020-12-19 00:41

    Use this function to check if wifi is on

    - (BOOL)isWifiOn {
        Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
    
        NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
        return (netStatus==ReachableViaWiFi);
    }
    

    similar code can be used to check reachabilityForInternetConnection but you have to check

    (netStatus==ReachableViaWiFi)
    

    if you care that it's over wifi AND

    (netStatus==ReachableViaWWAN)
    

    if you care that it's over WWAN

    0 讨论(0)
  • 2020-12-19 00:41

    I'm not sure if this is your problem, but I noticed that it matters when you call startNotifier. I was having a similar problem with never receiving notifications (but with shorter values for "never" -- I guess I'm not as paitent) until I moved the startNotifier call into some UI code, specifically applicationDidFinishLaunching.

    0 讨论(0)
  • 2020-12-19 00:51

    The reachability example from apple shows you how to use a notification, which is an event push model and supposed to be efficient, but I found that the notifications weren't always working properly for me. Sometimes they wouldn't fire, other times they would provide wrong information. So I ended up polling with a 2 second repeating timer, and checking for wifi with a procedure like the one described by stinkbutt above. Here's a good reference for timer implementation.

    0 讨论(0)
  • 2020-12-19 01:06

    I ran int the same problem. What I found in the end is that for WWAN or WiFi reachability, the notification callback is only called when there is a network change.

    In other words, check the current reachability immediately after you create the reachability object. Do not wait for the notification, because the notification will only be posted when next network change happens.

    For Internet/WWAN:

    self.wwanReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [wwanReach currentReachabilityStatus];
    if (networkStatus == ReachableViaWWAN) {
        // do something
    }
    

    For WiFi:

    self.wifiReach = [Reachability reachabilityForLocalWiFi];
    NetworkStatus networkStatus = [wifiReach currentReachabilityStatus];
    if (networkStatus == ReachableViaWiFi) {
        // do something
    }
    
    0 讨论(0)
提交回复
热议问题