2012-11-12 26 views
0

嗨,我在Apple的可達性代碼中遇到了一些問題。 我發現,即使設備正確連接到互聯網,最初可達性代碼會發送1個虛假通知(Networkstatus = NotReachable),然後發送幾個正確的通知(Networkstatus = ReachableViaWiFi)。 因此,當我在顯示UIAlertView時收到「NotReachable」通知時,即使設備連接到互聯網,應用程序仍會輸出uialertview,通知用戶設備未連接。Reachability + UIAlertView + false-positive

反正有避免這種不便嗎?

任何幫助將非常感激。

這是我的代碼:

在我的.h文件:

@property (nonatomic, retain) Reachability *hostReach; 

在我的.m文件:

- (void)viewDidLoad 
{ 
    self.hostReach = [Reachability reachabilityWithHostname:@"www.google.com"]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; 

    [_hostReach startNotifier]; 


    NetworkStatus netStatus = [self.hostReach currentReachabilityStatus]; 


    if(netStatus == NotReachable && _alertShowing==NO){ 

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                message:@"No internet connection found" 

                delegate:self 
              cancelButtonTitle:@"OK" 
              otherButtonTitles: nil]; 

     _alertShowing = YES; 

     [alert show]; 

    } 

    ... 

} 


-(void)reachabilityChanged:(NSNotification *)note { 

    Reachability* curReach = [note object]; 

NSParameterAssert([curReach isKindOfClass: [Reachability class]]);  

    NetworkStatus netStatus = [curReach currentReachabilityStatus]; 


    if(netStatus == NotReachable && _alertShowing==NO){ 

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                message:@"No internet connection found" 

                delegate:self 
              cancelButtonTitle:@"OK" 
              otherButtonTitles: nil]; 

     _alertShowing = YES; 

     [alert show]; 

    } 


-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{ 
    _alertShowing = NO; 

} 

回答

1

爲何使用reachabilityWithHostname:@"www.google.com"?此方法檢查特定主機的可達性(在您的案例中爲google.com)。如果Google可用或不可用,您會收到通知。 Google可能會阻止您,您將收到NotReachable的狀態。

嘗試使用:

//reachabilityForInternetConnection- checks whether the default route is available. 
// Should be used by applications that do not connect to a particular host 
+ (Reachability*) reachabilityForInternetConnection; 

,並採取上的方法描述here看看。

+0

非常感謝@EugeneK,我認爲解決了它。但是Google會因爲什麼原因阻止我? Ps我使用的是reachabilityWithHostname:@「www.google.com」,因爲在Apple的示例代碼中,他們使用的是reachabilityWithHostname:@「www.apple.com」,我認爲谷歌會擁有更可靠的服務器。 – puntotuning

+1

那麼,如果谷歌認爲你或你的用戶試圖通過發送大量數據包到他們的服務器來DDOS他們,你可能會考慮三次提出這樣的問題。 – CodaFi

+0

好吧,我瞭解你的觀點@CodaFi。但是如果是這樣的話,爲什麼蘋果使用reachabilityWithHostname:@「www.apple.com在他們的可達性示例代碼中? – puntotuning