美文网首页
Reachability 实时监控网络状态

Reachability 实时监控网络状态

作者: 齊同学 | 来源:发表于2019-05-16 16:44 被阅读0次
  • 从官网出下载Reachability.h/m文件,拖入工程

  • 调用Reachability.h头文件,并创建全局变量Reachability *internetReachability;

  • 在AppDelegate的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions方法中创建通知

 //添加一个系统通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //初始化
    internetReachability=[Reachability reachabilityForInternetConnection];
    //通知添加到Run Loop
    [internetReachability startNotifier];
    [self updateInterfaceWithReachability:internetReachability];
  • 实现通知方法
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}
  • 监测网络状态方法
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
    switch (netStatus) {
        case NotReachable:
            NSLog(@"====当前网络状态不可用=======");
            break;
        case ReachableViaWiFi:
            NSLog(@"====当前网络状态为Wifi=======");
            break;
        case ReachableViaWWAN:
            NSLog(@"====当前网络状态为流量=======keso");
            break;
    }
}

注:

  • 此方法能监测所有页面的网络状态,可是要在当前页面获取当前网络状态则需要使用AFNetWorking,如果不嫌麻烦那就一个一个写.

相关文章

网友评论

      本文标题:Reachability 实时监控网络状态

      本文链接:https://www.haomeiwen.com/subject/fvoiaqtx.html