iPhone应用程序,当他们没有连接到互联网时提醒用户?

dav*_*vis 1 iphone xcode alert uiwebview reachability

编写警报时,有什么简单的方法可以在用户未连接到Internet时向用户发出警告?我正在使用Xcode,现在当没有连接时,它只是uiwebview中的白色屏幕.

cho*_*own 6

在这里你可以检查wifi是否有连接,3g或没有连接:

if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi) {
    // Do something that requires wifi
} else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN) {
    // Do something that doesnt require wifi
} else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == NotReachable) {
    // Show alert because no wifi or 3g is available..
}
Run Code Online (Sandbox Code Playgroud)

Apple在此处提供了所有必需的Reachability api/source:Reachability Reference


我在所有项目中为自己制作了这些自定义便利功能:

+ (BOOL)getConnectivity {
    return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] != NotReachable;
}

+ (BOOL)getConnectivityViaWiFiNetwork {
    return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi;
}

+ (BOOL)getConnectivityViaCarrierDataNetwork {
    return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN;
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

if ([ServerSupport getConnectivity]) {
    // do something that requires internet...
else {
    // display an alert
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Network Unavailable" 
                                                     message:@"App content may be limited without a network connection!" 
                                                    delegate:self 
                                           cancelButtonTitle:@"OK" 
                                           otherButtonTitles:nil] autorelease];
    [alert show];
}
Run Code Online (Sandbox Code Playgroud)