IOS network detection Reachability uses Demo to detect 2, 3, 4G, iosreachability
You can download this Demo https://github.com/JanzTam/Reachability_Demo At Github
First, introduce the Reachability class of the system. If you do not know how to introduce it, In Xcode, press shift + command + 0 and search for Reachability. You can see the project selected in the figure and download it.
Reachability.png and import related. h files # import <CoreTelephony/CTTelephonyNetworkInfo. h>
After the introduction, modify the NetworkStatus enumeration in the Reachability. h file,
typedef enum : NSInteger { NotReachable = 0, ReachableViaWiFi, ReachableViaWWAN, kReachableVia2G, kReachableVia3G, kReachableVia4G} NetworkStatus;
Modify the Reachability. m file.
Find
- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
Modify the following code
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init]; NSString *currentRadioAccessTechnology = info.currentRadioAccessTechnology; if (currentRadioAccessTechnology) { if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) { returnValue = kReachableVia4G; } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) { returnValue = kReachableVia2G; } else { returnValue = kReachableVia3G; } return returnValue; } } if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection) { if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired) { returnValue = kReachableVia2G; return returnValue; } returnValue = kReachableVia3G; return returnValue; } returnValue = ReachableViaWWAN; }
How to use it?
Add in AppDelegate
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {// set the status bar [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault]; // monitor network conditions [[nsicationicationcenter defacenter center] addObserver: self selector: @ selector (reachabilityChanged :) name: jsonobject: nil]; hostReach = [Reachability failed: @ "www.baidu.com"]; [hostReach startNotifier];}
- (void)reachabilityChanged:(NSNotification *)note{ Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); NetworkStatus status = [curReach currentReachabilityStatus]; switch (status) { case NotReachable: break; case ReachableViaWiFi: case ReachableViaWWAN: break; case kReachableVia2G: break; case kReachableVia3G: break; case kReachableVia4G: break; }}