Reachability使用

首先在AppDelegate.h添加头文件"Reachability.h",导入框架SystemConfiguration.frame

下面是代码:

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

{

//开启网络状况的监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;

//开始监听,会启动一个run loop

[self.hostReach startNotifier];

}

-(void)reachabilityChanged:(NSNotification *)note

{

Reachability *currReach = [note object];

NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

//对连接改变做出响应处理动作

NetworkStatus status = [currReach currentReachabilityStatus];

//如果没有连接到网络就弹出提醒实况

self.isReachable = YES;

if(status == NotReachable)

{

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

[alert show];

[alert release];

self.isReachable = NO;

return;

}

if (status==kReachableViaWiFi||status==kReachableViaWWAN) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接信息" message:@"网络连接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

//        [alert show];

[alert release];

self.isReachable = YES;

}

}

然后在每个页面的viewWillAppear:加上:

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:YES];

AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];

if(appDlg.isReachable)

{

NSLog(@"网络已连接");//执行网络正常时的代码

}

else

{

NSLog(@"网络连接异常");//执行网络异常时的代码

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

[alert show];

[alert release];

}

}

这样就可以检查到在运行程序时网络突然的中断和连接。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 首先在AppDelegate.h添加头文件"Reachability.h",导入框架SystemConfigura...
    陈世美_阅读 14,324评论 3 13
  • 首先在AppDelegate.h添加头文件"Reachability.h",导入框架SystemConfigura...
    随遇而安_天下阅读 4,594评论 0 0
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 9,141评论 2 7
  • //AppDelegate.m - (BOOL)application:(UIApplication *)appl...
    偏执_cbbe阅读 1,397评论 0 0
  • 曾经,在这座小城的中心地段——最大的十字路口西北边有座美丽的小花园,两条主干道环绕着它,方圆不过百米。四周用铁栅栏...
    橘子669阅读 4,608评论 0 0