我在我的应用程序中使用AFNetworking与服务器通信。如何检查我的主机(服务器)是否可用,我应该在向服务器发送请求之前检查这一点。
答案 0 :(得分:1)
使用提供如下方法的AFNetworking 2.0,您可以检查而不是使用Reachability类。
- (void)viewDidLoad {
[super viewDidLoad];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
将开始监控设置为viewDidLoad
后,您可以使用Bellow方法检查课程的任何位置。
if ([[AFNetworkReachabilityManager sharedManager] isReachable])
{
NSLog(@"IS REACHABILE");
}
else
{
NSLog(@"NOT REACHABLE");
}
答案 1 :(得分:0)
您可以尝试以下代码:
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 你可以这样做:
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
}
}];
答案 2 :(得分:0)
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];