iOS - 网络连接类型监测

苹果官方网络连接类型监测代码包
打开项目压缩文件,把Reachability.h 和 Reachability.m加入到自己的项目中。

    self.reachability = [Reachability reachabilityWithHostName:@"https://www.baidu.com/"];
    switch ([self.reachability currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"当前网络不可用");
            break;
        case ReachableViaWiFi:
            NSLog(@"当前网络为WiFi");
            break;
        case ReachableViaWWAN:
            NSLog(@"当前网络为移动网络");
            break;
        default:
            break;
    }

    //如需动态监视网络变化,只需添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netChange:) name:kReachabilityChangedNotification object:nil];
    [self.reachability startNotifier];
- (void)netChange:(NSNotification *)notification{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"https://www.baidu.com/"];
    switch ([reachability currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"当前网络不可用");
            break;
        case ReachableViaWiFi:
            NSLog(@"当前网络为WiFi");
            break;
        case ReachableViaWWAN:
            NSLog(@"当前网络为移动网络");
            break;
        default:
            break;
    }
}

在合适的时机要注销掉网络监测和通知。

    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kReachabilityChangedNotification object:nil];
发布了38 篇原创文章 · 获赞 5 · 访问量 9073

猜你喜欢

转载自blog.csdn.net/zj382561388/article/details/103051768