iPhone判断是不是接入网络
iPhone判断是否接入网络
在这里介绍一种较为简单的判断是否连接网络的方法,首先要引入Reachability.h和.m文件,没有这两个文件的话,google之。然后在***AppDelegate.h中声明如下:
然后在.m中实现:
在需要判断的地方用:
在这里介绍一种较为简单的判断是否连接网络的方法,首先要引入Reachability.h和.m文件,没有这两个文件的话,google之。然后在***AppDelegate.h中声明如下:
NetworkStatus remoteHostStatus; NetworkStatus internetConnectionStatus; NetworkStatus localWiFiConnectionStatus; ... //Network @property NetworkStatus remoteHostStatus; @property NetworkStatus internetConnectionStatus; @property NetworkStatus localWiFiConnectionStatus; - (void) registerNetworkChecking; - (void) updateNetworkStatus;
然后在.m中实现:
- (void) registerNetworkChecking { [[Reachability sharedReachability] setHostName:@"www.baidu.com"]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:@"kNetworkReachabilityChangedNotification" object:nil]; //[self updateNetworkStatus]; } #pragma mark NetworkStatus Notification - (void)reachabilityChanged:(NSNotification *)note { //////NSLog(@"reachabilityChanged"); [self updateNetworkStatus]; } - (void)updateNetworkStatus { // Query the SystemConfiguration framework for the state of the device's network connections. self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus]; self.localWiFiConnectionStatus = [[Reachability sharedReachability] localWiFiConnectionStatus]; }
在需要判断的地方用:
***AppDelegate *appDelegate = (***AppDelegate *)[[UIApplication sharedApplication] delegate]; [appDelegate registerNetworkChecking]; if (appDelegate.remoteHostStatus == NotReachable) { //未联网 } else { //联网 }