前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IOS开发—网络监听

IOS开发—网络监听

原创
作者头像
好派笔记
修改2021-10-29 11:06:40
4600
修改2021-10-29 11:06:40
举报
文章被收录于专栏:好派笔记好派笔记

网络监听用到的类为Reachability.h,这个Xcode项目里面是不自带的,需要从github上面下载,在使用的时候记着导入SystemConfiguration.framework。

首先是在AppDelegate.m中设置网络监听

代码语言:javascript
复制
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

初始化:

代码语言:javascript
复制
_reachability = [Reachability reachabilityForInternetConnection];
[_reachability startNotifier];
[self updateInterfaceWithReachability:_reachability];

实现两个方法:

- (void) reachabilityChanged: (NSNotification* )note;//网络连接改变

- (void) updateInterfaceWithReachability: (Reachability*) curReach;//处理连接改变后的情况

下面是方法的具体实现,可根据情况自行改变:

代码语言:javascript
复制
// 连接改变
- (void) reachabilityChanged: (NSNotification* )note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability: curReach];
}

//处理连接改变后的情况
- (void) updateInterfaceWithReachability: (Reachability*) curReach {
    //对连接改变做出响应的处理动作。
    NetworkStatus status = [curReach currentReachabilityStatus];

    if (status == NotReachable) {
        _isReachable = NO;
        //没有连接到网络就弹出提实况
        UIAlertView *netAlert = [[UIAlertView alloc] initWithTitle:@"蜂窝移动数据已关闭" message:@"启用蜂窝移动数据或无线局域网来访问数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [netAlert show];
    } else {
        _isReachable = YES;
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档