Usually in the app some interface, need to get the data update interface through the network. By establishing network status monitoring, the application automatically refreshes the page data when the network becomes connected from disconnect, so it does not require the user to manually refresh the page, which improves the user experience of the product.
First, include the header file
#import "Reachability.h"
Add instance variables in Viewcontorller: reachability *_networkconn;
Second, the establishment of network change monitoring
Network changes include the change from disconnection to connection, connection to disconnection, and any situation where the app receives 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];
Where the Networkstatechange function is called when the network is changed.
Third, get the network status
After receiving the notification of network changes, the notification does not inform the current network status, so we do not know whether the current network is in a disconnected or connected, need to actively detect, 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;}
Four, refresh the interface
-(void) networkstatechange{ if ([self isnetworkenable]) { //In this refresh interface }}
iOS Development-Monitor network changes