I am using AFNetworking in my App for communicating with server. How can i check whether my host(server) is available or not, i should check this before i am sending a request to server.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Using AFNetworking 2.0 that provide method like below you can check instead of using Reachability class.
- (void)viewDidLoad {
[super viewDidLoad];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
After set start-monitoring in to viewDidLoad
you can check any where in to class using Bellow Method.
if ([[AFNetworkReachabilityManager sharedManager] isReachable])
{
NSLog(@"IS REACHABILE");
}
else
{
NSLog(@"NOT REACHABLE");
}
回答2:
You can try the following code:
Reachability *reach = [Reachability reachabilityWithHostname:@"google.com"];
if ([reach isReachable]) {
// Reachable
if ([reach isReachableViaWiFi]) {
// On WiFi
}
} else {
// Isn't reachable
[reach setReachableBlock:^(Reachability *reachblock)
{
// Now reachable
}];
[reach setUnreachableBlock:^(Reachability*reach)
{
// Now unreachable
}];
}
OR You can do like this:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://google.com"]];
[client setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == AFNetworkReachabilityStatusNotReachable) {
// Not reachable
} else {
// Reachable
}
if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
// On wifi
}
}];
回答3:
NSOperationQueue *operationQueue = self.operationQueue;
// This block is automatically invoked every time the network status changes
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
// we need to notify a delegete when internet connection is lost.
// use this delegate to notify the user.
//[delegate internetConnectionLost];
NSLog(@"No Internet Connection");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"Host available through WIFI");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"Host available through 3G");
break;
default:
NSLog(@"Unkown network status");
[operationQueue setSuspended:YES];
break;
}
}];
[self.reachabilityManager startMonitoring];