1. Why should I detect network status?
1.1 Let users know their network status, to prevent users from complaining "This application is too garbage, get data so Slow"
1.2 Improve user experience based on user's network status and intelligent processing
For example, some mobile browsers will automatically switch to no graph mode when the user network is detected as 2g/3g.
2. Manual Trigger
2.1 First download the Apple sample program reachability, get the sample program Reachability.h and REACHABILITY.M, add to your project
The code is as follows
-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
{
//Detect WiFi status
reachability *wifi = [reachability Reachabilityforlocalwifi];
//Detect mobile phone network status (2g/3g/wifi)
reachability *conn = [reachability reachabilityforinternetconnection];
if ([WIFI currentreachabilitystatus]! = notreachable) { //WiFi available
NSLog (@ "currently attached WiFi");
}else{ //No wifi
if ([conn currentreachabilitystatus]! = notreachable) { //have 2g/3g network
NSLog (@ "Currently attached to 2G/3G network");
}else{ //No 2G/3G network
NSLog (@ "currently not Connected");
}
}
}
2.2 Actual application, will not let the user to detect the network status manually, the following with the notification to achieve real-time detection network status
@property (Nonatomic,strong) reachability *coon;
Add notification
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (networkchange) Name: Kreachabilitychangednotification Object:nil];
Self.coon = [reachability reachabilityforinternetconnection];
Send Notifications
[Self.coon Startnotifier];
-(void) dealloc
{
[Self.coon Stopnotifier];
[[Nsnotificationcenter Defaultcenter] removeobserver:self];
}
-(void) NetworkChange
{
[Self checknetworkstate];
}
-(void) checknetworkstate
{
reachability *wifi = [reachability Reachabilityforlocalwifi];
reachability *conn = [reachability reachabilityforinternetconnection];
if ([WIFI currentreachabilitystatus]! = notreachable) {//WiFi available
NSLog (@ "currently attached WiFi");
}else{//No WiFi
if ([conn currentreachabilitystatus]! = notreachable) {//have 2g/3g network
NSLog (@ "Currently attached to 2G/3G network");
}else{//No 2G/3G network
NSLog (@ "currently not Connected");
}
}
}
IOS Detects network status