1:我們項目中經(jīng)常會用到獲取用戶當前的網(wǎng)絡狀態(tài),是否有網(wǎng)蹭沛,是否是wifi情況下
準備工作
1:從蘋果官網(wǎng)上下載Reachability.zip章鲤,并且解壓,這個類是蘋果提供給我們帚呼,用于檢測網(wǎng)絡狀態(tài)皱蹦,下載解壓好,拖拽到我們項目中
2:添加框架:SystemConfiguration.framework
開始編寫代碼
1:導入Reachability.h頭文件
2:寫一個屬性@property(nonatomic,strong)Reachability* reach;
3:
//添加監(jiān)聽沈自,當網(wǎng)絡發(fā)生變化的時候枯途,會發(fā)出通知籍滴,我們只需要監(jiān)聽就行(不要忘了移除監(jiān)聽)
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[self.reach startNotifier]; //開始監(jiān)聽,會啟動一個run loop
}
//實現(xiàn)方法孽惰,可以根據(jù)不同的狀態(tài)來做想做的操作
- (void)reachabilityChanged: (NSNotification*)note
{
Reachability*curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
NetworkStatus status=[curReach currentReachabilityStatus];
switch (status) {
case ReachableViaWiFi:
case kReachableVia4G:
case kReachableVia2G:
case kReachableVia3G:
case NotReachable:
break;
default:
break;
}
}
4:判斷當前網(wǎng)絡狀態(tài)
NSString *netconnType = NULL;
Reachability* reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
switch ([reach currentReachabilityStatus]) {
case NotReachable:
netconnType = @"NotReachable";
break;
case ReachableViaWiFi:
netconnType = @"WIFI";
break;
case ReachableViaWWAN:
netconnType = @"WWAN";
break;
case kReachableVia2G:
netconnType = @"2G";
break;
case kReachableVia3G:
netconnType = @"3G";
break;
case kReachableVia4G:
netconnType = @"4G";
break;
case kReachableViaOther:
netconnType = @"OTHER";
break;
default:
netconnType = NULL;
break;
}
return netconnType;