可能重复:
How to check for an active Internet Connection on iPhone SDK?
在iOS应用程序中实现Reachability(通知用户没有Internet连接的代码)的最简单方法是什么?
答案 0 :(得分:5)
我在appDelegate
中这样做了@interface myAppDelegate : NSObject <UIApplicationDelegate> {
IBOutlet noInternetViewController *NoInternetViewController;
BOOL isShowingNoInternetScreen;
}
//at top
#import "Reachability.h"
//somewhere under @implementation
-(void)checkInternetConnection {
Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
if (!isShowingNoInternetConnectionScreen) {
[self.navigationController pushViewController:NoInternetViewController animated:YES];
isShowingNoInternetConnectionScreen = YES;
}
}
else if (isShowingNoInternetConnectionScreen) {
[self.navigationController popViewControllerAnimated:YES];
isShowingNoInternetConnectionScreen = NO;
}
}
//inside application:didFinishLaunchingWithOptions: or in application:didFinishLaunching
isShowingNoInternetConnectionScreen = NO;
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(checkInternetConnection) userInfo:nil repeats:YES];
我正在使用导航控制器,但如果你不是,那么只需更改pushViewController:animated:to presentModalViewController:animated:并更改popViewControllerAnimated:to dismissModalViewController
您显然需要在Interface Builder中设置一个与IBOutlet绑定的视图控制器。只要你想让用户在没有连接时看到它就可以了。