reachability real-time monitoring of network changes

Source: Internet
Author: User

Reachability is a real-time observation of the changes in the network control, such as when your phone in the WiFi situation, he will detect the environment, when in the case of GPS changes in the environment, when in a network-free situation is an environment. Let's take a look at the usage of reachability,

1. In the case of reachability, first introduce systemconfiguration;

Reachability.h:

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>


typedef Enum:nsinteger {
notreachable = 0,
Reachableviawifi,
Reachableviawwan
} networkstatus;


extern NSString *kreachabilitychangednotification;


@interface Reachability:nsobject


+ (Instancetype) Reachabilitywithhostname: (NSString *) hostName;


+ (Instancetype) reachabilitywithaddress: (const struct sockaddr_in *) hostaddress;


+ (instancetype) reachabilityforinternetconnection;


+ (instancetype) Reachabilityforlocalwifi;

-(BOOL) Startnotifier;
-(void) stopnotifier;

-(NetworkStatus) currentreachabilitystatus;

reachability. M:

#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 1

static void Printreachabilityflags (Scnetworkreachabilityflags flags, const char* comment)
{
#if kshouldprintreachabilityflags

NSLog (@ "reachability Flag Status:%c%c%c%c%c%c%c%c%c%s\n",
(Flags & Kscnetworkreachabilityflagsiswwan)? ' W ': '-',
(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, scnetworkreachabilityflags flags, void* info)
{
#pragma unused (target, flags)
Nscassert (info! = NULL, @ "info is null in Reachabilitycallback");
Nscassert ([(__bridge nsobject*) info iskindofclass: [reachability class]], @ "info was wrong class in Reachabilitycallback ");

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 NO
Scnetworkreachabilityref _reachabilityref;
}

+ (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;
}


+ (Instancetype) reachabilitywithaddress: (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)
{
Returnvalue->_reachabilityref = reachability;
Returnvalue->_alwaysreturnlocalwifistatus = NO;
}
}
Return returnvalue;
}



+ (Instancetype) reachabilityforinternetconnection
{
struct sockaddr_in zeroaddress;
Bzero (&zeroaddress, sizeof (zeroaddress));
Zeroaddress.sin_len = sizeof (zeroaddress);
zeroaddress.sin_family = af_inet;

return [Self reachabilitywithaddress:&zeroaddress];
}


+ (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};

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 & kscnetworkreachabilityflagsinterventionrequired) = = 0)
{
/*
... and no [user] intervention is needed ...
*/

returnvalue = Reachableviawifi;
}
}

if ((Flags & kscnetworkreachabilityflagsiswwan) = = Kscnetworkreachabilityflagsiswwan)
{
/*
... but WWAN connections be 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;
}


-(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

The above is only a third-party components, coupled with some of the personal packaging of some of the methods, the following we will be specific to each controller, to detect changes in the network environment

Controller.h

#import <UIKit/UIKit.h>
#import "Reachability.h"

@interface Reachviewcontroller:uiviewcontroller
-(void) reachabilitychanged: (nsnotification *) Note;
-(void) Updateinterfacewithreachability: (reachability *) reachability;
-(void) Configuretextfield: (Uitextfield *) TextField ImageView: (Uiimageview *) ImageView reachability: (reachability *) reachability;

@end

Controller.m

#import "ReachViewController.h"
#import "MBProgressHUD.h"
#import "HUD.h"
@interface Reachviewcontroller ()
@property (nonatomic) reachability *hostreachability;
@property (nonatomic) reachability *internetreachability;
@property (nonatomic) reachability *wifireachability;

@end

@implementation Reachviewcontroller

-(void) Viewdidload {
[Super Viewdidload];




[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (reachabilitychanged:) Name: Kreachabilitychangednotification Object:nil];
NSString *remotehostname = @ "www.apple.com";
NSString *remotehostlabelformatstring = nslocalizedstring (@ "Remote host:%@", @ "remote host label format string");

self.hostreachability = [reachability reachabilitywithhostname:remotehostname];
[Self.hostreachability Startnotifier];
[Self updateInterfaceWithReachability:self.hostReachability];


}


-(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 Reachableviawwan:
{
[HUD promptwithstring:@ "is using traffic, it is recommended to use WiFi" onView:self.view];

}
Break
Case Reachableviawifi:
{
[HUD promptwithstring:@ "WiFi is connected" onView:self.view];

}
Break
Default
Break
}




}

-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
When your network environment changes, you can see it in real time. The code does not have any bugs, new demo, copy and paste can see the effect, if your development environment error is the version of the problem.

reachability real-time monitoring of network changes

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.