In the network application, sometimes needs to the user equipment network state to carry on the real-time monitoring, has two purposes:
(1) Let users understand their own network status, to prevent some misunderstandings (such as the use of strange applications incompetent)
(2) According to the user's network status of intelligent processing, save user traffic, improve user experience
WiFi network: Automatically download HD images
4G/3G network: Download only thumbnails
No network: Only offline cached data is displayed
The following two methods are commonly used:
(1), using the Apple method to detect the iOS device network environment for the library reachablity
(2), using the Afnetworkreachabilitymanager in the AFN frame to monitor the change of the network state
First, Apple has provided a sample program called reachability, which makes it easier for developers to detect network status
Please download the sample from Apple Web site before use: http://xiazai.jb51.net/201608/yuanma/Reachability (jb51.net). rar
Then add Reachability.h and REACHABILITY.M to your project and refer to Systemconfiguration.framework, which you can use.
3 network states are defined in reachability:
typedef enum:nsinteger {
notreachable = 0,//no connection
Reachableviawifi,//Use 3G/GPRS network
Reachableviawwan// Use WiFi network
} networkstatus;
We can start real-time monitoring after the program starts.
APPDELEGATE.M @interface appdelegate () @property (nonatomic, strong) reachability *reachability; @end//program initiator, start network monitoring-(void) applicationdidfinishlaunching: (uiapplication *) application {//Set up network detection site NSString *r
Emotehostname = @ "www.apple.com";
self.reachability = [reachability reachabilitywithhostname:remotehostname];
To set the notification function when network state changes [[Nsnotificationcenter defaultcenter] addobserver:self selector: @selector (reachabilitychanged:)
name:@ "Knetworkreachabilitychangednotification" object:nil];
[Self updatestatus];
}-(void) Reachabilitystatuschange: (nsnotification *) Notification {reachability* Curreach = [Notification Object];
Nsparameterassert ([Curreach iskindofclass:[reachability class]);
[Self Updateinterfacewithreachability:curreach]; }-(void) Updateinterfacewithreachability: (reachability *) reachability {if (reachability = = _reachability) {Net
Workstatus netstatus = [reachability currentreachabilitystatus]; SwitcH (netstatus) {case notreachable: {NSLog (@ "No network!)
");
Break
Case Reachableviawwan: {NSLog (@ "4g/3g");
Break
Case Reachableviawifi: {NSLog (@ "WiFi");
Break
}}-(void) Dealloc {[_reachability stopnotifier];
[[Nsnotificationcenter Defaultcenter] removeobserver:self name:kreachabilitychangednotification Object:nil];
}
Two, use the Afnetworkreachabilitymanager in the AFN frame to listen for changes to the state of the network
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.