Вопрос

Hi I have read some posts and see that I can use "reachability" sample from Apple to check if the current device is run on Wi-Fi or cellular and decide if a connection can be fired. However I have a lots of webviews and HTTP calls in my app on different classes, so I am afraid I have to call the check in every single method which will start a connection. I would like to ask if there is any way to check the status of the network and disallow all traffic on cellular? Thanks a lot.

Это было полезно?

Решение

You are looking for the ReachableViaWiFi network status, which is broadcast via NSNotification. You can setup that up in your code like this:

@property (nonatomic, assign) NetworkStatus currentNetStatus;

...

- (void) startListeningForWifi{
            Reachability* hostReach = [Reachability reachabilityWithHostName:@"hostName"];
            [hostReach startNotifier];

            // reachability set up
            // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
            // method "reachabilityChanged" will be called. 
            [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
}

- (void)reachabilityChanged: (NSNotification* )note{
    Reachability *curReach = [note object];
    self.currentNetStatus = [curReach currentReachabilityStatus];
}

Then it's easy to check the currentNetStatus before you make a network call. If that is not equal to ReachableViaWiFi then you are not on wifi.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top