簡介
在開發(fā)的過程中盏浇,常常需要對當(dāng)前的網(wǎng)絡(luò)狀態(tài)進行檢測,通常我們嘗借助一些第三方框架,例如AFNetworking中檢測網(wǎng)絡(luò)是否連接的方法來進行網(wǎng)絡(luò)檢測,但是其弊端就是當(dāng)網(wǎng)絡(luò)狀態(tài)發(fā)生改變的時候绪钥,不可能實時的知道網(wǎng)絡(luò)狀態(tài)發(fā)生改變,必須通過調(diào)用相應(yīng)的方法才可以知道关炼,在網(wǎng)絡(luò)上查找了一些方法后程腹,才知道原來蘋果提供了相應(yīng)的實時檢測網(wǎng)絡(luò)的類Reachability,蘋果的官方框架盗扒,只不過沒有集成到xcode里面去跪楞,可到蘋果官方網(wǎng)站上面去下載下載地址缀去,只需要導(dǎo)入調(diào)用即可.
使用
使用過程中侣灶,只需添加頭文件"Reachability.h",導(dǎo)入框架SystemConfiguration.framework,使用方法如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window =[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor=[UIColor whiteColor];
KKLoginViewController *login = [[KKLoginViewController alloc] init];
self.window.rootViewController = login;
[self.window makeKeyAndVisible];
//實時檢測網(wǎng)絡(luò)的方法
[self checkNetWorkOntime];
[self setCrshLog];
//[self checkVersion];
return YES;
}
//實時監(jiān)聽網(wǎng)絡(luò)狀態(tài)
-(void)checkNetWorkOntime {
//創(chuàng)建網(wǎng)絡(luò)監(jiān)聽
[AppDelegate getInstance].netStatus=1;//默認(rèn)網(wǎng)絡(luò)好的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//創(chuàng)建網(wǎng)絡(luò)監(jiān)聽對象
self.reachability = [Reachability reachabilityForInternetConnection];
//開始檢測
[self.reachability startNotifier];
[AppDelegate getInstance].netStatus=[self.reachability currentReachabilityStatus];
}
//網(wǎng)絡(luò)狀態(tài)結(jié)果變化后的處理
- (void)reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus status = [curReach currentReachabilityStatus];
[AppDelegate getInstance].netStatus=status;
[[NSNotificationCenter defaultCenter]postNotificationName:NetWorkChangeNotification object:nil userInfo:@{@"status":@(status)}];
}