首页 > 代码库 > ios 判断网络

ios 判断网络

      网络的重要性,相信大家都知道了。这次介绍下ios是如何判断网络的好坏的,由于在开发中用到,所以分享给大家,很简单。这里要用到Reachability封装类来实现,大家可以网上去下载Reachability.m 和Reachability.h文件,需要我提供请留言。

具体代码:

在AppDelegate里面实现:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

    self.window.backgroundColor = [UIColorwhiteColor];

    //初始化登陆页

    LoginViewController *loginCtrl = [[LoginViewControlleralloc] init];

   self.window.rootViewController = loginCtrl;

    

    //判断网络

    [[NSNotificationCenterdefaultCenter] addObserver:self

                                            selector:@selector(reachabilityChanged:)

                                                name:kReachabilityChangedNotification

                                              object:nil];

    

    Reachability * reach = [ReachabilityreachabilityWithHostname:@"www.baidu.com"];

    

    [reachstartNotifier];

    

//    MainViewController *mainController = [[MainViewController alloc] init];

//    self.window.rootViewController = mainController;

    [self.windowmakeKeyAndVisible];

    return YES;

}

//通知

-(void)reachabilityChanged:(NSNotification*)note

{

   Reachability * reach = [note object];

    

   if([reach isReachable])

    {

        NSLog(@"Notification Says Reachable");

    }

   else

    {

        UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:nilmessage:@"网络已断开"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil];

        [alertViewshow];

        NSLog(@"Notification Says Unreachable");

    }

}

代码很简单,大家可以用来试试!!!



ios 判断网络