在iOS 7上获取互联网/网络的状态

时间:2013-12-31 23:49:28

标签: ios iphone ios7 network-programming reachability

我有这段代码:

BOOL status = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

但由于某种原因它总是返回YES,即使我的设备处于飞行模式,蜂窝数据关闭,而我的电脑Wifi关闭。通知中心代码工作正常:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

self.reachability = [Reachability reachabilityWithHostname:@"www.google.com"];

[self.reachability startNotifier];

是什么给出了?

1 个答案:

答案 0 :(得分:2)

您的设备可以通过ReachableViaWWAN or ReachableViaWiFi

访问

有三个NetworkStatus可用。

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


/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 This method is used to provide wifi network current status.
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
- (NetworkStatus *)notifyNetworkStatus:(Reachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];

    NSString* statusString = @"Network Mode Changed / Connection closed!!";

    @try
    {
        switch (netStatus)
        {
            case NotReachable:
            {
                statusString = @"No network Access!! Connection closed";
                break;
            }
            case ReachableViaWWAN:
            {
                statusString = @"Network Mode Changed / Connection reachable only via WWAN!!";
                break;
            }
            case ReachableViaWiFi:
            {
                statusString = @"Network Mode Changed / Connection reachable via WiFi";
                break;
            }
            default:
            {
                break;
            } 

        }
    }
    @catch (NSException *exception)
    {
        NSLog(@"%s\n Exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
    }
}

下载并查看developer.apple.com- Reachability application