在iOS应用程序中实现Reachability(通知用户没有Internet连接的代码)的最简单方法是什么?
我在appDelegate中这样做了
在appDelegate.h中:
@interface myAppDelegate : NSObject <UIApplicationDelegate> {
IBOutlet noInternetViewController *NoInternetViewController;
BOOL isShowingNoInternetScreen;
}
Run Code Online (Sandbox Code Playgroud)
在appDelegate.m中
//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];
Run Code Online (Sandbox Code Playgroud)
我正在使用导航控制器,但如果你不是,那么只需更改pushViewController:animated:to presentModalViewController:animated:并更改popViewControllerAnimated:to dismissModalViewController
您显然需要在Interface Builder中设置一个与IBOutlet绑定的视图控制器.只要你想让用户在没有连接时看到它就可以了.
| 归档时间: |
|
| 查看次数: |
3900 次 |
| 最近记录: |