在这里介绍一种较为简单的判断是否连接网络的方法,首先要引入Reachability.h和.m文件,没有这两个文件的话,google之。然后在***AppDelegate.h中声明如下:
1. NetworkStatus remoteHostStatus;
2. NetworkStatus internetConnectionStatus;
3. NetworkStatus localWiFiConnectionStatus;
4.
5. ...
6.
7. //Network
8. NetworkStatus remoteHostStatus;
9. NetworkStatus internetConnectionStatus;
10. NetworkStatus localWiFiConnectionStatus;
11. (void) registerNetworkChecking;
12. (void) updateNetworkStatus;
NetworkStatus remoteHostStatus;
NetworkStatus internetConnectionStatus;
NetworkStatus localWiFiConnectionStatus;
...
//Network
@property NetworkStatus remoteHostStatus;
@property NetworkStatus internetConnectionStatus;
@property NetworkStatus localWiFiConnectionStatus;
- (void) registerNetworkChecking;
- (void) updateNetworkStatus;
然后在.m中实现:
Obj-c代码
1. (void) registerNetworkChecking
2. {
3. [[Reachability sharedReachability] setHostName:@"www.baidu.com"];
4. [[NSNotificationCenter defaultCenter] addObserver:self
5. selector:@selector(reachabilityChanged:)
6. name:@"kNetworkReachabilityChangedNotification"
7. object:nil];
8. //[self updateNetworkStatus];
9.
10. }
11. mark NetworkStatus Notification
12. (void)reachabilityChanged:(NSNotification *)note
13. {
14. //NSLog(@"reachabilityChanged");
15. [self updateNetworkStatus];
16. }
17.
18. - (void)updateNetworkStatus
19. {
20. // Query the SystemConfiguration framework for the state of the device's network connections.
21. self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
22. self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
23. self.localWiFiConnectionStatus = [[Reachability sharedReachability] localWiFiConnectionStatus];
24. }
- (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];
}
在需要判断的地方用:
Obj-c代码
1. *appDelegate = (***AppDelegate *)[[UIApplication sharedApplication] delegate];
2. registerNetworkChecking];
3. (appDelegate.remoteHostStatus == NotReachable)
4. {
5. //未联网
6. }
7. else
8. {
9. //联网
10. }