1.在github下载Reachability框架
https://github.com/tonymillion/Reachability
2.导入系统框架 SystemConfiguration.framework
3.导入Reachability框架里面 Reachability.h,Reachability.m的两个文件
4.在appDelegate.m 实现
#import "AppDelegate.h"
#import "Reachability.h"
@interface AppDelegate ()
@property(nonatomic,strong)Reachability*hostReah;
/// 记录网络改变之前的网络状态@property(nonatomic,assign)NetworkStatus status;```
@end
@implementation AppDelegate
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)name:kReachabilityChangedNotification object:nil];
Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
[reach startNotifier];
//开始监听,会启动一个runloop
[self.hostReach startNotifier];
return YES;
}
/// 通知 调用的方法
-(void)reachabilityChanged:(NSNotification *)notification
Reachability *reach = [notification object];
if([reach isKindOfClass:[Reachability class]]){
NetworkStatus status = [reach currentReachabilityStatus];
//如果网络状态发生改变
if (status != self.status) {
//记录当前网络状态
self.status = status;
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:[self isInternetWith:status] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
}
}
}
///返回根据status返回当前网络状态
-(NSString*)isInternetWith:(NetworkStatus)status
```{
switch (status) {
case NotReachable:
return @"没网";
break;
case ReachableViaWiFi:
return @"WIFI上网";
break;
case ReachableViaWWAN:
return @"移动上网";
break;
default:
break;
}
}```
网友评论