[英]How do I use Reachability to check if there's an internet connection, and if not, do something. (Basically use as a boolean.)
我已經閱讀了Reachability頁面上的代碼,但是不清楚在if語句類型場景中如何使用它。
例如,用戶點擊刷新按鈕,觸發refresh
方法(如圖所示,是嗎?),如果存在互聯網連接,我希望刷新數據,但是如果沒有,我要發送否通知互聯網。
如何達到可觸及性?
我將只使用以下代碼,但根據結果在每個塊中將一個變量設置為一個值,然后再對其進行查看。 這似乎不那么優雅,但是如果這是唯一的方法,那就去吧。
// 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];
我的應用程序就是這樣做的-在塊中向主線程中的self發送一條消息-說hostChanged:(BOOL)狀態。 然后,您的自類可以維護狀態的公共變量,或者其他對象可以偵聽的通知。
我的應用程序在應用程序委托中具有此功能,因此其他對象很容易到達它。
請注意,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......
}
快速檢查網絡連接的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.