2011-10-02 69 views
4

我想檢查,看看用戶是否有一個有效的互聯網連接。這是我實施它的方式。這似乎很好地工作,但問題是,它總是顯示不存在在我的iPhone模擬器無連接(uialert來了),即使我的WiFi打開或關閉。有沒有人知道我做錯了什麼? 感謝您的幫助!檢查是否有一個有效的互聯網連接iPhone的情況

Reachability *r= [Reachability reachabilityWithHostName:@"http://www.google.com"]; 
    NetworkStatus internetStatus= [r currentReachabilityStatus]; 

if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) 
    { 

     UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"No internet" message:@"No internet connection found. Please try again later" 
                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 
    } 

else { 

// execute code in app 

} 

回答

6

這是我如何在我的應用程序做到了:

Reachability *reachability = [Reachability reachabilityForInternetConnection]; 
NetworkStatus internetStatus = [reachability currentReachabilityStatus]; 

if(internetStatus == NotReachable) { 
    UIAlertView *errorView; 

    errorView = [[UIAlertView alloc] 
       initWithTitle: NSLocalizedString(@"Network error", @"Network error") 
       message: NSLocalizedString(@"No internet connection found, this application requires an internet connection to gather the data required.", @"Network error") 
       delegate: self 
       cancelButtonTitle: NSLocalizedString(@"Close", @"Network error") otherButtonTitles: nil]; 

    [errorView show]; 
    [errorView autorelease]; 
} 

是什麼做的是,它會檢查的internetconnection,而不是它是否能達到一個域。如果沒有互聯網連接(wifi或celluar),它將顯示一個UIAlertView消息(本地化)。

+0

謝謝你真是太棒了! – Teddy13

0

不檢查。無線電往往開始打開,建立公正的可達性報告沒有網絡連接後(可達報告說,沒有網絡可能就是啓動這個過程,從而使得它自己的答案是錯誤的幾秒鐘後)。

+0

對不起,你說的「收音機」是什麼意思?我從過去的用戶那裏聽說過,如果你不檢查,應用商店會拒絕? – Teddy13

+0

我已經通過應用商店所需的所有網絡活動和我研究這個頗有幾分批准了三個應用程序。你不必檢查可達性細節,如果你不想,我懷疑大多數應用程序不。但是,如果需要網絡但網絡不存在,則您需要在應用中使用用戶友好的行爲。這意味着沒有凍結,掛起,如果應用程序需要互聯網,但它是不可用最肯定顯示警報或相似。 – johnbakers