2011-10-02 66 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