网络的重要性,相信大家都知道了。这次介绍下ios是如何判断网络的好坏的,由于在开发中用到,所以分享给大家,很简单。这里要用到Reachability封装类来实现,大家可以网上去下载Reachability.m 和Reachability.h文件,需要我提供请留言。
具体代码:
在AppDelegate里面实现:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
{
self.window = [[UIWindow
alloc] initWithFrame:[[UIScreen
mainScreen] bounds]];
self.window.backgroundColor = [UIColor
whiteColor];
//初始化登陆页
LoginViewController *loginCtrl = [[LoginViewController
alloc]
init];
self.window.rootViewController = loginCtrl;
//判断网络
[[NSNotificationCenter
defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability
reachabilityWithHostname:@"www.baidu.com"];
[reach
startNotifier];
// MainViewController *mainController = [[MainViewController alloc] init];
// self.window.rootViewController = mainController;
[self.window
makeKeyAndVisible];
return
YES;
}
//通知
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note
object];
if([reach isReachable])
{
NSLog(@"Notification Says Reachable");
}
else
{
UIAlertView *alertView = [[UIAlertView
alloc] initWithTitle:nil
message:@"网络已断开"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alertView
show];
NSLog(@"Notification Says Unreachable");
}
}
代码很简单,大家可以用来试试!!!