我正在尝试让我的应用确定用户是否具有互联网连接以及他们拥有何种类型的连接。我导入了SystemConnection框架和Reachability .h和.m文件。
在我的viewController.h中,我有以下内容:
#import "Reachability.h"
Reachability* reachability;
和vc.m
//notification for network status change
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil];
[reachability startNotifier];
//check connectivity
[self checkConnectivity];
:
- (void) checkConnectivity {
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
NSLog(@"no connection");
} else if (remoteHostStatus == ReachableViaWiFi) {
NSLog(@"wifi");
} else if (remoteHostStatus == ReachableViaWWAN) {
NSLog(@"cell");
}
}
这在启动时运行良好。我记录了进度,它按预期返回:
2013-07-29 09:35:17.084 OAI_Project_Template[6095:c07] not connected - network change
2013-07-29 09:35:17.093 OAI_Project_Template[6095:c07] wifi- check connectity
但是,如果我打开或关闭wifi连接,则永远不会调用handleNetworkChange。
- (void) handleNetworkChange : (NSNotification*) notification {
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
isConnected = NO;
NSLog(@"not connected - network change");
} else if (remoteHostStatus == ReachableViaWiFi) {
NSLog(@"wifi - network change");
} else if (remoteHostStatus == ReachableViaWWAN) {
NSLog(@"cell");
}
}
我环顾四周,看到了很多类似的问题,但解决方案似乎都是按照我的方式设置的。
如果重要的话,我在模拟器中工作。任何帮助,将不胜感激。
答案 0 :(得分:0)
https://github.com/tonymillion/Reachability是apple reachability类的自定义替代品
答案 1 :(得分:0)
这是我必须检测的网络。基本上,我所需要的只是检测应用程序是否可以访问互联网上的服务器,一旦发布通知,根据访问权限检查访问和处理。确保仅在应用程序位于前台时注册可访问性。
// Called from applicationDidBecomeActive
- (void) startMonitoring
{
//Register for change in reachability
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
// Setup a target server to detect if a host on the internet can be accessed . For example www.apple.com. Defined as instance variable
hostReach = [Reachability reachabilityWithHostName: @"www.apple.com"];
[hostReach startNotifier];
}
- (void)reachabilityChanged:(NSNotification *)note
{
//NSLog(@"%s %@", __FUNCTION__, note);
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability: curReach];
}
- (void)updateInterfaceWithReachability: (Reachability*) curReach
{
// Check if the host site is online
NetworkStatus hostStatus = [hostReach currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"%s No access - ", __FUNCTION__);
break;
}
case ReachableViaWiFi:
{
// Check for LAN switch
NSLog(@"%s WIFI Available - ", __FUNCTION__);
break;
}
case ReachableViaWWAN:
{
// Disable LAN switch
NSLog(@"%s WIFI NOT Available ", __FUNCTION__);
break;
}
}
}