Use a system approach to monitor network status
- The method of system is to realize the monitoring of network state through notification mechanism.
-
Steps to implement network status monitoring
- Define a member variable of type reachability to save the state of the network
@property (nonatomicstrong) Reachability *reachability;
- Observers registered as notification hubs
// 在通知中心注册观察者[[NSNotificationCenter defaultCenter] addObserver:self selector:@selectorobject:nil];/*** getNetworkStatus:监听到通知的回调方法* kReachabilityChangedNotification:通知的类型,即网络状态发生改变时,触发通知* object:传递给getNetworkStatus回调方法的参数*/// 获取并保存网络状态self.reachability = [Reachability reachabilityForInternetConnection];// 开始监听[self.reachability startNotifier];
- Judging the state of the network in the triggering method of hearing notifications
- (void)getNetworkStatus{ if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus != NotReachable) { NSLog(@"是WIFI"); } elseif ([Reachability reachabilityForInternetConnection].currentReachabilityStatus != NotReachable) { NSLog(@"是手机自带网络"); } else { NSLog(@"网络有问题"); }}
- Remove the observer from the Notification Center, stop listening, and empty the network listener
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [self.reachability stopNotifier]; self.reachabilitynil;}
Using Afnetworking to monitor network status
- Monitoring network status via AFN is relatively simple
-
To implement network status monitoring
- Get an instance of Afnetworkreachabilitymanager
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
- Set the block that the manager callback when the network changes
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"----当前网络状态---%zd", status);}];/*** status:表示当前网络的状态,是个枚举类型变量,具有以下取值* AFNetworkReachabilityStatusUnknown = -1* AFNetworkReachabilityStatusNotReachable = 0* AFNetworkReachabilityStatusReachableViaWWAN = 1* AFNetworkReachabilityStatusReachableViaWiFi = 2*/
[manager startMonitoring];
The latest status of this blog will be synced to Sina Weibo account: secular island
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS Network -06-Monitor the iphone's network status