IOS development-monitoring network changes
Generally, you need to obtain the data update interface through the network on some APP interfaces. By setting up a network status listener, an application automatically refreshes page data after the network changes from disconnected to connected. Therefore, you do not need to manually refresh the page to improve the user experience of the product.
1. include header files
#import "Reachability.h"
At the same time, add the instance variable Reachability * _ networkConn in viewcontorroller;
2. Establish a network change listener
Network changes include switching from disconnection to connection and connection to disconnection. In either case, the app will receive a notification of network changes. Add the following code to the viewDidLoad method:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil]; _networkConn = [Reachability reachabilityForInternetConnection]; [_networkConn startNotifier];
The networkStateChange function is called when the network changes.
3. Obtain the network status
After the network change notification is received, the notification does not inform you of the current network status. Therefore, we do not know whether the current network is disconnected or connected. We need to actively detect the network. The detection method is as follows:
- (BOOL)isNetworkEnable{ BOOL flag = YES; Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"]; switch ([r currentReachabilityStatus]) { case NotReachable: flag = NO; break; case ReachableViaWWAN: break; case ReachableViaWiFi: break; default: break; } return flag;}
4. Refresh the interface
-(Void) networkStateChange {if ([self isNetworkEnable]) {// refresh the interface here }}