1、添加Reachability.h和Reachability.m到工程中;
2、在Frameworks里添加SystemConfiguration.framework;
3、在AppDelegate.m中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
//开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
reachability =[[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[reachability startNotifier];
return YES;
}
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability: curReach];
}
//处理连接改变后的情况
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
//对连接改变做出响应的处理动作。
NetworkStatus status = [curReach currentReachabilityStatus];
switch (status) {
case NotReachable:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"NotReachable"
message:@""
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
}
break;
case kReachableViaWWAN:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"kReachableViaWWAN"
message:@""
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
}
break;
case kReachableViaWiFi:
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"kReachableViaWiFi"
message:@""
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
}
break;
default:
break;
}
}