首先项目中包含框架
然后在delegate中:
//初始化添加网络
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//开启网络状况的监听
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
Reachability* hostReach = [Reachability reachabilityWithHostname:@"www.google.com"] ;//可以以多种形式初始化
[hostReach startNotifier]; //开始监听,会启动一个run loop
return YES;
}
// 连接改变
- (void) reachabilityChanged: (NSNotification* )note
{
Reachability* curReach = [note object];
//对连接改变做出响应的处理动作。
NetworkStatus status = [curReach currentReachabilityStatus];
if (status == NotReachable) {
NSLog(@"no net");
}
if (status == ReachableViaWiFi) {
NSLog(@"wifi");
}
if (status == ReachableViaWWAN) {
NSLog(@"wan");
}
}