標籤:
1.為什麼要檢測網路狀態?
1.1 讓使用者知道自己的網路狀態,防止使用者埋怨"這個應用太垃圾,擷取資料那麼慢"
1.2 根據使用者的網路狀態,智能處理,提升使用者體驗
例如某些手機瀏覽器,檢測到使用者網路是2G/3G時,會自動切換為無圖模式
2.手動觸發
2.1 首先下載蘋果的樣本程式Reachability, 取得樣本程式裡的Reachability.h和Reachability.m, 添加到自己項目裡
代碼如下
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 檢測WIFI狀態
Reachability *WIFI = [Reachability reachabilityForLocalWiFi];
// 檢測手機連網狀態(2G/3G/WIFI)
Reachability *conn = [Reachability reachabilityForInternetConnection];
if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI
NSLog(@"當前連著WIFI");
}else{ //無WIFI
if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G網路
NSLog(@"當前連著2G/3G網路");
}else{ //無2G/3G網路
NSLog(@"當前沒連網");
}
}
}
2.2 實際應用中,不會讓使用者手動去檢測網路狀態,下面用通知實現即時檢測網路狀態
@property (nonatomic,strong) Reachability *coon;
// 添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange) name:kReachabilityChangedNotification object:nil];
self.coon = [Reachability reachabilityForInternetConnection];
// 發送通知
[self.coon startNotifier];
- (void)dealloc
{
[self.coon stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)networkChange
{
[self checkNetworkState];
}
- (void)checkNetworkState
{
Reachability *WIFI = [Reachability reachabilityForLocalWiFi];
Reachability *conn = [Reachability reachabilityForInternetConnection];
if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI
NSLog(@"當前連著WIFI");
}else{ //無WIFI
if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G網路
NSLog(@"當前連著2G/3G網路");
}else{ //無2G/3G網路
NSLog(@"當前沒連網");
}
}
}
iOS 檢測網路狀態