Apple 已经很好地为我们创建了一个完整的示例。它被称为可达性(Apple 链接)。这是它的要点:
在 .h 文件中:
// declare Reachability, you no longer have a singleton but manage instances
Reachability* reachability;
在 .m 文件中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable)
{
NSLog(@"no");
}
else if (remoteHostStatus == ReachableViaWiFiNetwork)
{
NSLog(@"wifi");
}
else if (remoteHostStatus == ReachableViaCarrierDataNetwork)
{
NSLog(@"cell");
}
.....
- (void) handleNetworkChange:(NSNotification *)notice
{
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable)
{
NSLog(@"no");
}
else if (remoteHostStatus == ReachableViaWiFiNetwork)
{
NSLog(@"wifi");
}
else if (remoteHostStatus == ReachableViaCarrierDataNetwork)
{
NSLog(@"cell");
}
}