我已经设置了一些方法来检查我的应用中的网络状态。
在我的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];
}
//]]]]]]
有什么想法吗?
答案 0 :(得分: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中的某个示例基于。
编辑:看起来尼克发现了它......:)
答案 1 :(得分:1)
我建议使用Apple的Reachability类。 Here是Apple的示例App。
Reachability示例应用程序 演示了如何使用 SystemConfiguration框架来 监控iPhone的网络状态 或iPod touch。特别是它 演示如何知道IP何时可以 被路由,交通时间 通过无线广域路由 网络(WWAN)接口,如EDGE 或3G。