4

我已经设置了一些方法来检查我的应用程序中的网络状态。

在我的viewDidLoad方法中,我调用initNetworkCheck

[self initNetworkCheck];
[super viewDidLoad];
if(internetActive == NO){     
    compose.enabled = NO;
}

所以我想在启动时检查硬件是否有互联网连接。问题是它总是给我 NO,但当我记录它时,internetActive 实际上是 YES。

//[[[[[[network check methods
-(void)checkNetworkStatus:(NSNotification *)notice{
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus) {
        case NotReachable:{
            self.internetActive = NO; 
            break;
        }
        case ReachableViaWiFi:{
            self.internetActive = YES;
            break;
        }
        case ReachableViaWWAN:{
            self.internetActive = YES;
            break;
        }
    }
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus){
        case NotReachable:{
            self.hostActive = NO;
            break;
        }
        case ReachableViaWiFi:{
            self.hostActive = YES;
            break;
        }
        case ReachableViaWWAN:{
            self.hostActive = YES;
            break;
        }
    }

}
-(void)initNetworkCheck{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    hostReachable = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
    [hostReachable startNotifier];
}
//]]]]]]

有任何想法吗?

4

2 回答 2

3

我个人使用以下内容:

typedef enum
{
    NoConnection = 0,
    WiFiConnected,
    WWANConnected
} NetworkStatus;

NetworkStatus getNetworkStatus ( )
{
    struct sockaddr_in nullAddress;

    bzero(&nullAddress, sizeof(nullAddress));
    nullAddress.sin_len = sizeof(nullAddress);
    nullAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*) &nullAddress);

    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityGetFlags(ref, &flags);

    if (!(flags & kSCNetworkReachabilityFlagsReachable))
        return NoConnection;

    if (!(flags & kSCNetworkReachabilityFlagsConnectionRequired))
        return WiFiConnected;

    if (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ||
        (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)) &&
        !(flags & kSCNetworkReachabilityFlagsInterventionRequired))
        return WiFiConnected;

    if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
        return WWANConnected;

    return NoConnection;
}

我忘记了确切的位置,但是SDK中有一个基于此的示例。

编辑:看起来尼克找到了它...... :)

于 2011-04-14T11:37:02.403 回答
1

我建议使用 Apple 的 Reachability 类。是Apple的示例应用程序。

Reachability 示例应用程序演示了如何使用 SystemConfiguration 框架来监视 iPhone 或 iPod touch 的网络状态。特别是,它演示了如何知道何时可以路由 IP,以及何时通过无线广域网 (WWAN) 接口(如 EDGE 或 3G)路由流量。

于 2011-04-14T11:36:31.920 回答