如果用系統(tǒng)的方法需要導入 Reachability.h Reachability.m
@interface ViewController ()
@property (nonatomic, strong) Reachability r1; /*< <#屬性名#> */
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// nullable : 代表可以為nil
// __nonnull : 代表不能為nil
[manager GET:@"www.520it.com" parameters:nil success:^ void(NSURLSessionDataTask * task, id responseObjc) {
NSLog(@"成功的回調(diào)");
} failure:^ void(NSURLSessionDataTask * task, NSError * error) {
NSLog(@"失敗的回調(diào)");
}];
*/
// 1.創(chuàng)建Reachability對象
self.r1 = [Reachability reachabilityForLocalWiFi];
// 2.給Reachability對象注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkStatus) name:kReachabilityChangedNotification object:nil];
// 3.讓Reachability對象發(fā)送網(wǎng)絡改變的通知
[self.r1 startNotifier];
}
(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}(void)getNetworkStatus
{
if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus != NotReachable) {
NSLog(@"當前是蜂窩網(wǎng)");
}else if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus != NotReachable)
{
NSLog(@"當前是蜂窩網(wǎng)");
}else
{
NSLog(@"沒有網(wǎng)絡");
}
}(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent )event
{
/
// 1.創(chuàng)建Reachability對象
// 創(chuàng)建一個蜂窩網(wǎng)的Reachability對象
Reachability *r1 = [Reachability reachabilityForInternetConnection];
// 2.獲取當前對象的網(wǎng)絡狀態(tài), 如果不是NotReachable值, 那么就代表當前的網(wǎng)絡狀態(tài)是我們創(chuàng)建的類型
if(r1.currentReachabilityStatus != NotReachable)
{
NSLog(@"當前是蜂窩網(wǎng)");
}
// 創(chuàng)建一個局域網(wǎng)的Reachability對象
Reachability *r2 = [Reachability reachabilityForLocalWiFi];
if(r2.currentReachabilityStatus != NotReachable)
{
NSLog(@"當前是蜂窩網(wǎng)");
}
*/
}
-
(void)afnReachability
{
// 1.創(chuàng)建網(wǎng)絡監(jiān)聽管理者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];// 2.設置網(wǎng)絡變化的回調(diào)
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 只要用戶的網(wǎng)絡發(fā)生改變, 就會調(diào)用這個block
/*
AFNetworkReachabilityStatusUnknown = 不能識別,
AFNetworkReachabilityStatusNotReachable = 沒有網(wǎng)絡,
AFNetworkReachabilityStatusReachableViaWWAN = 蜂窩網(wǎng),
AFNetworkReachabilityStatusReachableViaWiFi = 局域網(wǎng),
*/
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"蜂窩網(wǎng)");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"局域網(wǎng)");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"沒有網(wǎng)絡");
break;
default:
NSLog(@"不能識別");
break;
}
}];// 3.開始監(jiān)聽
[manager startMonitoring];
}
@end