ios AFNetworking 2.0 可达性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19775646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AFNetworking 2.0 Reachability
提问by 7c9d6b001a87e497d6b96fbd4c6fdf
I am trying to determine if the user is connected to the internet by using AFNetworking 2.0 and the "AFNetworkReachabilityManager", but it doesen't seem to work. It's always return that there is a valid internet connection, even though the internet is turned off. This is my code:
我正在尝试使用 AFNetworking 2.0 和“AFNetworkReachabilityManager”来确定用户是否已连接到互联网,但它似乎不起作用。即使互联网已关闭,也总是会返回有效的互联网连接。这是我的代码:
-(BOOL)connected {
__block BOOL reachable;
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"No Internet Connection");
reachable = NO;
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WIFI");
reachable = YES;
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G");
reachable = YES;
break;
default:
NSLog(@"Unkown network status");
reachable = NO;
break;
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
}];
return reachable;
}
This method is called from my viewDidLoad method. Is there something wrong with my code, since it isn't working?
这个方法是从我的 viewDidLoad 方法调用的。我的代码有问题吗,因为它不起作用?
回答by backofthecup
You're making this more difficult than it needs to be. Try this:
你让这变得比需要的更困难。尝试这个:
- (void)viewDidLoad {
[super viewDidLoad];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
- (BOOL)connected {
return [AFNetworkReachabilityManager sharedManager].reachable;
}
If you also want to be notified when the status changes, then implement setReachabilityStatusChangeBlock
如果您还想在状态更改时收到通知,则实现 setReachabilityStatusChangeBlock
Hope this helps!
希望这可以帮助!
回答by Marcelo Fabri
That's because that block is only executed when reachability changes.
那是因为该块仅在可达性发生变化时才执行。
To get the current status, you can do this:
要获取当前状态,您可以执行以下操作:
- (BOOL)connected {
return [AFNetworkReachabilityManager sharedManager].reachable;
}
回答by RonLugge
You have two code errors that will prevent your code from working.
您有两个代码错误会阻止您的代码工作。
First, your call to 'start monitoring' occurs inside the block that is fired in response to reachability changes -- therefore, the block will never fire (unless you start monitoring elsewhere).
首先,您对“开始监控”的调用发生在响应可达性变化而触发的块内——因此,该块永远不会触发(除非您在其他地方开始监控)。
Second, there are no guarantees on when that block will fire. As a result, you'll always see 'reachable' return whatever value it was initialized to -- apparently this is usually null. Even if you fix the first error, there's no guarantee (and it's actually rather unlikely) that the block will fire before you return.
其次,无法保证该块何时触发。因此,您总是会看到 'reachable' 返回它初始化为的任何值——显然这通常是 null。即使您修复了第一个错误,也无法保证(实际上不太可能)该块会在您返回之前触发。
Finally, on a more general level, you're also trying to test in a synchronous manner code that can onlybe executed asynchronously. Which is to say, it's impossible for the reachability manager to accurately determine reachability instantaneously. It can say 'I think I'm on WiFi' or 'I think I'm on 3G', but it also needs to check to see if it can actually reachthe internet (hence the name reachability) before it can be certain. Reachability isn't just about 'I have a wifi' or 'I have a 3g' connection, it's also about whether you can reach the internet through it. This means the device actually has to send a request, and while this can, technically, be done in a synchronous manner, every single rule in the book insists that network code mustbe done asynchronously, and for good reason. If you did is synchronously, you'd block your UI until the network call returns... possibly a good 30, 40, 50, even 60 seconds later, depending on the relevant timeouts.
最后,在更一般的层面上,您还尝试以同步方式测试只能异步执行的代码。也就是说,可达性管理器不可能即时准确地确定可达性。它可以说“我认为我在使用 WiFi”或“我认为我在使用 3G”,但它也需要在确定之前检查它是否真的可以访问互联网(因此名称可达性)。可达性不仅仅与“我有 wifi”或“我有 3g”连接有关,还与您是否可以通过它访问互联网有关。这意味着设备实际上必须发送请求,虽然这在技术上可以以同步方式完成,异步完成,并且有充分的理由。如果你是同步的,你会阻塞你的 UI,直到网络调用返回......可能是 30、40、50,甚至 60 秒后,取决于相关的超时。
What you should do is start the reachability singleton monitoring in your app did load method of the app delegate, then retrieve it's data later. Without knowing the structure of your app I won't even try to guarantee accuracy, but that should at least help, somewhat.
您应该做的是在您的应用程序中启动可达性单例监控确实加载了应用程序委托的方法,然后稍后检索它的数据。在不知道您的应用程序结构的情况下,我什至不会尝试保证准确性,但这至少应该有所帮助。
回答by Balaji G
Try this,
尝试这个,
In AppDelegate, didFinishLaunchingWithOptionsmethod
在AppDelegate 中,didFinishLaunchingWithOptions方法
{ // SETUP AFNETWORKING's NETWORK INDICATOR AND REACHABILITY
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
In HttpManagerclass,
在HttpManager类中,
- (BOOL)isNetworkRechable {
if ([AFNetworkReachabilityManager sharedManager].reachable) {
if ([AFNetworkReachabilityManager sharedManager].isReachableViaWiFi)
NSLog(@"Network reachable via WWAN");
else
NSLog(@"Network reachable via Wifi");
return YES;
}
else {
NSLog(@"Network is not reachable");
return NO;
}
}
In yourViewController,
在yourViewController 中,
[[HttpManager sharedObject] isNetworkRechable];
Note: Don't check networkRechabilityat very first. Because it will not work. So please wait minimum 1 sec to check it.
注意:不要一开始就检查networkRechability。因为它不会工作。所以请至少等待 1 秒来检查它。
回答by For Guru
As per my experience,
根据我的经验,
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
takes a moment to execute setReachabilityStatusChangeBlock
so there is no use returning value from -(BOOL)connected
.
执行需要一些时间,setReachabilityStatusChangeBlock
因此从-(BOOL)connected
.
So you can perform some task once network is connected/disconnected.
因此,一旦网络连接/断开连接,您就可以执行一些任务。
The following function is best to check connectivity at the spot (synchronously):
以下功能最好在现场(同步)检查连通性:
[AFNetworkReachabilityManager sharedManager].reachable;
回答by user5664685
The other answers are wrong! It's better to use this to check availabilty:
其他答案都错了!最好使用它来检查可用性:
if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
The reason why is because initially networkReachabilityStatus will be set to AFNetworkReachabilityStatusUnknown until the change status block is called and this stops your code from thinking that network is unavailable when it is not.
原因是因为最初 networkReachabilityStatus 将设置为 AFNetworkReachabilityStatusUnknown 直到调用更改状态块,这会阻止您的代码认为网络不可用时不可用。
回答by Bassant Ashraf
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self checkNetworkReachability];
}
+(BOOL) isReachable{
return [AFNetworkReachabilityManager sharedManager].reachable;
}
+(void) checkNetworkReachability{
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
// Check the reachability status and show an alert if the internet connection is not available
switch (status) {
case -1:
// AFNetworkReachabilityStatusUnknown = -1,
NSLog(@"The reachability status is Unknown");
break;
case 0:
// AFNetworkReachabilityStatusNotReachable = 0
NSLog(@"The reachability status is not reachable");
break;
case 1:
NSLog(@"The reachability status is reachable via wan");
[[NSNotificationCenter defaultCenter] postNotificationName:@"Network_Reachable" object:nil];
break;
case 2:
// AFNetworkReachabilityStatusReachableViaWiFi = 2
NSLog(@"The reachability status is reachable via WiFi");
[[NSNotificationCenter defaultCenter] postNotificationName:@"Network_Reachable" object:nil];
break;
default:
break;
}
}];
}