[英]How do I use Reachability to check if there's an internet connection, and if not, do something. (Basically use as a boolean.)
I've read over the code on Reachability 's page, but I'm unclear as to how I'd use it in an if statement type scenario. 我已经阅读了Reachability页面上的代码,但是不清楚在if语句类型场景中如何使用它。
For example, the user taps the refresh button, firing the refresh
method (go figure, eh?) and if there is an internet connection, I want the refresh of data to occur, but if not, I want to send a notification of no internet. 例如,用户点击刷新按钮,触发
refresh
方法(如图所示,是吗?),如果存在互联网连接,我希望刷新数据,但是如果没有,我要发送否通知互联网。
How would I achieve something like this with Reachability? 如何达到可触及性?
Would I just use code like the following but have a variable set to a value in each block depending on the result, and just look at it after. 我将只使用以下代码,但根据结果在每个块中将一个变量设置为一个值,然后再对其进行查看。 That seems less than elegant, but if it's the only way, so be it.
这似乎不那么优雅,但是如果这是唯一的方法,那就去吧。
// allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// set the blocks
reach.reachableBlock = ^(Reachability*reach)
{
NSLog(@"REACHABLE!");
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
};
// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];
My app did just that - send a message in the block to self on the main thread - say hostChanged:(BOOL)state. 我的应用程序就是这样做的-在块中向主线程中的self发送一条消息-说hostChanged:(BOOL)状态。 Your self class can then maintain a public ivar of the state, or and a notification other objects can listen for.
然后,您的自类可以维护状态的公共变量,或者其他对象可以侦听的通知。
My app had this function in the app delegate so it was easy for other objects to get to it. 我的应用程序在应用程序委托中具有此功能,因此其他对象很容易到达它。
Note that it takes iOS tens of seconds to determine the state, so my code launched with he assumption of UP. 请注意,iOS需花费数十秒钟来确定状态,因此我的代码是在假设UP的情况下启动的。
-(BOOL)NetworkConnectionCheck {
Reachability *reachability = [Reachability reachabilityForInternetConnection];
return [reachability isReachable];
}
-(void)viewDidLoad {
if (!self.NetworkConnectionCheck) { // checks active network connection
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"There are no active wifi or data connection!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alert show];
} else {
// do your refresh stuff here......
}
Quick way to check network connection. 快速检查网络连接的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.