How to detect wifi network change in iOS

梦想的初衷 提交于 2019-12-10 10:56:21

问题


I am working on iOS application and I would need to detect when network changes either from Wifi connection to another Wifi connection or between Wifi and 3G.

I have tried using Reachability library but it seems it does not detect changes between Wifi connections. What can I use?

Target of the application would be App Store so I can't use private methods of Apple.

UPDATE: After some testing I have found out that when testing using simulator it works perfectly. I get notifications without any problem. iphone problem, maybe?

Thanks in advance


回答1:


Please refer this link https://stackoverflow.com/a/19256197/1382157

Other way,

- (BOOL)isReachable {
return [self isReachableViaWWAN] || [self isReachableViaWiFi];
}

- (BOOL)isReachableViaWWAN {// If this return true, means it is connected to 3g
return self.networkReachabilityStatus == 
AFNetworkReachabilityStatusReachableViaWWAN;
}

- (BOOL)isReachableViaWiFi { // If this return true, means it is connected to wifi
return self.networkReachabilityStatus == 
AFNetworkReachabilityStatusReachableViaWiFi;
}

make sure you initialize class properly and do

[self.manager.reachabilityManager startMonitoring]; 



回答2:


please see first Reachibility

After Importing class write in .h

 Reachability* reachability;

.m class

 [[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"); 
} 
} 


来源:https://stackoverflow.com/questions/45959705/how-to-detect-wifi-network-change-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!