【发布时间】:2014-11-25 21:43:44
【问题描述】:
我正在使用 Tony Million 的 Reachability 版本(问题与 Apple 的 Reachability 版本相同)来检查我的应用程序是否有活动的互联网连接。
这就是我想要的:
当视图加载或出现时,它会检查是否有互联网连接。如果没有,如果显示警报,单击时会再次尝试,直到有活动连接。
如果有连接,则视图正常加载。当 Reachability 通知连接丢失时,它会再次显示相同的警报。 这是我的实际代码:
//in the implementation:
BOOL internetActivated;
- (void)viewDidLoad
{
[super viewDidLoad];
[self testInternetConnection];
NSLog(@"%d", internetActivated);
if(internetActivated == NO)
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Pas de connexion internet" message:@"Une connexion est requise pour utiliser l'application" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Réessayer", nil];
[alert show];
}
else {
[self onAppearFunction];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[self testInternetConnection];
if(internetActivated == NO)
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Pas de connexion internet" message:@"Une connexion est requise pour utiliser l'application" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Réessayer", nil];
[alert show];
}
else {
[self onAppearFunction];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
{
[self viewDidLoad];
}
}
- (void)testInternetConnection
{
__unsafe_unretained typeof(self) weakSelf = self;
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
// Internet is reachable
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
internetActivated = YES;
NSLog(@"Yayyy, we have the interwebs!");
});
};
// Internet is not reachable
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
internetActivated = NO;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Pas de connexion internet" message:@"Une connexion est requise pour utiliser l'application" delegate:weakSelf cancelButtonTitle:nil otherButtonTitles:@"Réessayer", nil];
[alert show];
NSLog(@"Someone broke the internet :(");
});
};
[internetReachableFoo startNotifier];
}
多个问题:
1) InternetActivated 以“NO”开头,即使我在测试 if 条件之前调用了[self testInternetConnection]。它应该更新为YES,不是吗?
2) 即使我有互联网连接,testInternetConnection 方法中的UIAlertView 也会不断被调用。实际上:第二个警报被调用了三到四次(在 testInternet 方法中),然后第一个警报视图被调用了三到四次,即viewDidLoad 方法中的那个。
顺便说一句,我注意到这个 NSLog:NSLog(@"Yayyy, we have the interwebs!");
每次 [self testInternetConnection] 调用都会被调用不止一次。
我完全搞乱了警报调用,这让我发疯了!
感谢您的帮助
更新:
我设法通过在加载时将 BOOL 设置为 true 并在单击离开时将其设置为 false 来避免多个警报,以避免多个警报堆积。唯一的问题是,我希望 internetActivated BOOL 在我检查它之前更新 if...
【问题讨论】:
-
当然我会,一旦它运作良好!感谢您的帮助。
标签: ios uialertview reachability