iOS Development-reachability Real-time detection of wifi,2g/3g/4g/network status

Source: Internet
Author: User

recently encountered a feature is based on the user's current network, users do not need to prompt the Internet, if it is WiFi can recommend some picture news, if the 3G mode is set to no Diagram mode, access to network status is relatively simple, after all, China's current traffic is still a relatively expensive state, The day the user discovers that the app consumes too much traffic might kill the app. However, the reachability of Apple have solved the above problems, it is more convenient to use, the specific slightly simple analysis.

Reachability.h Header File Code:

#import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import < Netinet/in.h>//http://www.cnblogs.com/xiaofeixiangtypedef Enum:nsinteger {notreachable = 0,ReachableViaWiFi, Reachableviawwan} networkstatus;extern nsstring *kreachabilitychangednotification; @interface reachability:nsobject /*! * Use to check the reachability of a given host name. */+ (Instancetype) Reachabilitywithhostname: (NSString *) hostname;/*! * Use to check the reachability of a given IP address. */+ (Instancetype) reachabilitywithaddress: (const struct sockaddr_in *) hostaddress;/*! * Checks Whether the default route is available. Should is used by applications and that does not connect to a particular host. */+ (instancetype) reachabilityforinternetconnection;/*! * Checks whether a local WiFi connection is available. */+ (instancetype) reachabilityforlocalwifi;/*! * Start listening for reachability notifications in the current run loop. */-(BOOL) startnotifier;-(void) Stopnotifier;-(NetworkStatus) currentreachabilitystatus;/*! * WWAN May is available, but the active until a connection has been established. WiFi may require a connection for VPN on Demand. */-(BOOL) connectionrequired; @end

REACHABILITY.M file:

#import <arpa/inet.h> #import <ifaddrs.h> #import <netdb.h> #import <sys/socket.h> #import < corefoundation/corefoundation.h> #import "Reachability.h" nsstring *kreachabilitychangednotification = @ " Knetworkreachabilitychangednotification "; #pragma mark-supporting functions#define kshouldprintreachabilityflags 1static void Printreachabilityflags (scnetworkreachabilityflags flags, const char* comment) {#if          Kshouldprintreachabilityflags NSLog (@ "reachability Flag Status:%c%c%c%c%c%c%c%c%c%s\n",//Current network 2g/3g/4g Cellular network (Flags & Kscnetworkreachabilityflagsiswwan)? ' W ': '-',//whether the network can reach (Flags & kscnetworkreachabilityflagsreachable)? ' R ': '-', (Flags & kscnetworkreachabilityflagstransientconnection)? ' t ': '-', (Flags & kscnetworkreachabilityflagsconnectionrequired)? ' C ': '-', (Flags & kscnetworkreachabilityflagsconnectionontraffic)? ' C ': '-', (Flags & KSCnetworkreachabilityflagsinterventionrequired)? ' I ': '-', (Flags & Kscnetworkreachabilityflagsconnectionondemand)? ' D ': '-', (Flags & kscnetworkreachabilityflagsislocaladdress)? ' l ': '-', (Flags & kscnetworkreachabilityflagsisdirect)? ' d ': '-', comment); #endif}static void Reachabilitycallback (scnetworkreachabilityref target, Scnetworkr Eachabilityflags flags, void* info) {#pragma unused (target, flags) Nscassert (info! = NULL, @ "info is null in REACHABILITYC Allback "); Nscassert ([(__bridge nsobject*) info iskindofclass: [reachability class]], @ "info was wrong class in Reachabilitycallback    ");    Http://www.cnblogs.com/xiaofeixiang reachability* noteobject = (__bridge reachability *) info;    Post a notification to notify the client, the network reachability changed. [[Nsnotificationcenter Defaultcenter] postnotificationname:kreachabilitychangednotification object:noteobject];} #pragma mark-rEachability implementation@implementation Reachability{bool _alwaysreturnlocalwifistatus;//default is Noscnetworkreachabilityref _reachabilityref;} Instantiate via Domain name Blog Park-fly_elephant+ (instancetype) Reachabilitywithhostname: (NSString *) hostname{reachability* returnvalue = NULL; Scnetworkreachabilityref reachability = Scnetworkreachabilitycreatewithname (NULL, [HostName utf8string]); if ( reachability = null) {returnvalue= [[Self alloc] init];if (returnvalue! = null) {Returnvalue->_reachabilityref = Reachability;returnvalue->_alwaysreturnlocalwifistatus = NO;}} return returnvalue;} Instantiate reachability+ (instancetype) reachabilitywithaddress by IP address: (const struct sockaddr_in *) hostaddress{ Scnetworkreachabilityref reachability = scnetworkreachabilitycreatewithaddress (Kcfallocatordefault, (const struct SOCKADDR *) hostaddress); reachability* returnvalue = null;if (reachability! = null) {returnvalue = [[Self alloc] init];if (returnvalue! = null) {Retu Rnvalue->_reachabilityref = reachability;returnvalue->_alwaysreturnlocalwifistatus = NO;}} return returnvalue;} Detect if you can connect directly to Internet + (instancetype) reachabilityforinternetconnection{struct sockaddr_in Zeroaddress;bzero (&    zeroaddress, sizeof (zeroaddress)); Zeroaddress.sin_len = sizeof (zeroaddress); zeroaddress.sin_family = af_inet; return [self reachabilitywithaddress:&zeroaddress];} Detects if the current network can be wifi+ (instancetype) reachabilityforlocalwifi{struct sockaddr_in Localwifiaddress;bzero (& localwifiaddress, sizeof (localwifiaddress)); Localwifiaddress.sin_len = sizeof (localwifiaddress); localwifiaddress.sin_family = af_inet;//in_linklocalnetnum is defined in <netinet/in.h> as 169.254.0.0. LOCALWIFIADDRESS.SIN_ADDR.S_ADDR = htonl (in_linklocalnetnum); reachability* returnvalue = [self reachabilitywithaddress: &localwifiaddress];if (returnvalue! = NULL) {    Returnvalue->_alwaysreturnlocalwifistatus = YES;} return returnvalue;} #pragma mark-start and stop notifier-(BOOL) Startnotifier{bool returnvalue = NO; ScnetworkreachabilityconteXT context = {0, (__bridge void *) (self), NULL, NULL, NULL}; The Scnetworkreachabilitysetcallback function specifies a target//when the device changes to the target link state (such as disconnecting or re-connecting). The callback Reachabilitycallback function, if (Scnetworkreachabilitysetcallback (_reachabilityref, Reachabilitycallback, & Context) {if (Scnetworkreachabilityschedulewithrunloop (_reachabilityref, cfrunloopgetcurrent (),    Kcfrunloopdefaultmode) {returnvalue = YES;}} return returnvalue;} -(void) stopnotifier{if (_reachabilityref! = NULL) {Scnetworkreachabilityunschedulefromrunloop (_reachabilityref, Cfrunloopgetcurrent (), Kcfrunloopdefaultmode);}} -(void) dealloc{[self stopnotifier];if (_reachabilityref! = NULL) {cfrelease (_reachabilityref);}} #pragma mark-network Flag handling-(networkstatus) Localwifistatusforflags: (scnetworkreachabilityflags) flags{ Printreachabilityflags (Flags, "localwifistatusforflags"); NetworkStatus returnvalue = notreachable;if ((Flags & kscnetworkreachabilityflagsreachable) && (Flags & KscnetworkreachabilityflagsisDirect) {returnvalue = Reachableviawifi;} return returnvalue;} -(NetworkStatus) Networkstatusforflags: (scnetworkreachabilityflags) Flags{printreachabilityflags (Flags, " Networkstatusforflags ") if ((Flags & kscnetworkreachabilityflagsreachable) = = 0) {//The target host is not reachable.    return notreachable;}         NetworkStatus returnvalue = notreachable;if ((Flags & kscnetworkreachabilityflagsconnectionrequired) = = 0) {/*         If the target host is reachable and no connection are required then we'll assume (for now) so you ' re on Wi-Fi ... */returnvalue = Reachableviawifi;}        if (((Flags & kscnetworkreachabilityflagsconnectionondemand)! = 0) | |  (Flags & kscnetworkreachabilityflagsconnectionontraffic)! = 0)) {/* ... and the connection is On-demand (or on-traffic) if the calling application is using the Cfsocketstream or higher APIs ... */if (Flags &am P kscnetworkreachabilityflagsinterventionrequired) = = 0) {/*             ... and no [user] intervention is needed ... */returnvalue = Reachableviawifi; }}if (Flags & Kscnetworkreachabilityflagsiswwan) = = Kscnetworkreachabilityflagsiswwan) {/* ... but WWAN c         Onnections is OK if the calling application is using the Cfnetwork APIs.    */returnvalue = Reachableviawwan;} return returnvalue;} -(BOOL) Connectionrequired{nsassert (_reachabilityref! = null, @ "connectionrequired called with null Reachabilityref"); Scnetworkreachabilityflags flags;if (Scnetworkreachabilitygetflags (_reachabilityref, &flags)) {return (Flags    & kscnetworkreachabilityflagsconnectionrequired);} return NO;} Gets the current network status-(NetworkStatus) Currentreachabilitystatus{nsassert (_reachabilityref! = NULL, @ "Currentnetworkstatus Called with NULL scnetworkreachabilityref "); NetworkStatus returnvalue = notreachable;    Scnetworkreachabilityflags flags; if (Scnetworkreachabilitygetflags (_reachabilityref, &flags)) {if (_alwaysreturnlocAlwifistatus) {returnvalue = [self localwifistatusforflags:flags];}    Else{returnvalue = [self networkstatusforflags:flags];}} return returnvalue;} @end

Implementation in Appdelegate:

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {    Add a system notification    [[nsnotificationcenter defaultcenter] addobserver:self selector: @selector (reachabilitychanged:) Name:kreachabilitychangednotification Object:nil];    Initialize    self.internetreachability=[reachability reachabilityforinternetconnection];    The notification is added to the run Loop    [self.internetreachability startnotifier];    [Self updateinterfacewithreachability:_internetreachability];    return YES;}

callback function:

-(void) reachabilitychanged: (nsnotification *) note{    reachability* Curreach = [Note Object];    Nsparameterassert ([Curreach iskindofclass:[reachability class]]);    [Self Updateinterfacewithreachability:curreach];} -(void) Updateinterfacewithreachability: (reachability *) reachability{    networkstatus netstatus = [Reachability Currentreachabilitystatus];    Switch (netstatus) {case        notreachable:            NSLog (@ "= Current network status is not up to =======http://www.cnblogs.com/xiaofeixiang") ;            break;        Case Reachableviawifi:            NSLog (@ "= = Current network status is wifi======= Blog Park-fly_elephant");            break;        Case Reachableviawwan:            NSLog (@ "= = Current network status is 3g=======keso");            break;    }}

Mode test WiFi mode-wuwifi-connected to WiFi, showing the following results:

If you instantiate directly through host, you can also:

    NSString *remotehostname = @ "Www.cnblogs.com/xiaofeixiang";    self.hostreachability = [reachability reachabilitywithhostname:remotehostname];

iOS Development-reachability Real-time detection of wifi,2g/3g/4g/network status

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.