In the development of iOS applications I always use the network, but also to monitor the network connection situation, when the network changes when the corresponding event processing work. The following explains how to use reachability to monitor the network edge connection situation.
To use reachability for network monitoring, the Reachability.h and REACHABILITY.M must be piloted into two pieces.
Declare a global reachability class in the. h file, with the following code:
#import
#import "Reachability.h"
@interface Appdelegate:uiresponder {
Reachability *hostreach;
}
@property (Strong, nonatomic) UIWindow *window;
@end
Add the corresponding code in the. m file
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions
{
Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]];
Override point for customization after application launch.
monitoring network conditions
[[Nsnotificationcenter Defaultcenter] Addobserver:self
Selector: @selector (reachabilitychanged:)
Name:kreachabilitychangednotification
Object:nil];
Initialize the Reachability class and add a monitored URL.
Hostreach = [reachability reachabilitywithhostname:@ "http://blog.sina.com.cn/u/2526279194"];
Start monitoring
[Hostreach Startnotifier];
Self.window.backgroundColor = [Uicolor Whitecolor];
[Self.window makekeyandvisible];
return YES;
}
#pragma mark-monitors network conditions and calls when the network changes
-(void) reachabilitychanged: (nsnotification *) Note {
reachability* Curreach = [Note Object];
Nsparameterassert ([Curreach iskindofclass: [reachability class]]);
NetworkStatus status = [Curreach currentreachabilitystatus];
if (status = = Notreachable) {
Uialertview *alert = [[Uialertview alloc] Initwithtitle:nil
message:@ "Notreachable"
Delegate:nil
cancelbuttontitle:@ "YES" otherbuttontitles:nil];
[Alert show];
alert = nil;
}
}
Real-time monitoring of network connectivity using reachability