如何检查iOS或macOS网络连接是否可用?

开发过程中,需要监听网络的连接状态,那么如何去监听呢?

一、监听——网络连接状态变化自动调用回调

Swift版本

  1. 通过CocoaPods或者Carthage安装Reachability,地址:https://github.com/ashleymills/Reachability.swift

  2. 通过闭包测试reachability

    let reachability = Reachability()!
    
    reachability.whenReachable = { reachability in
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }
    
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    

Objective-C版本

  1. 添加SystemConfigurationframework到项目中

  2. 添加Tony Million’s 版本的Reachability.hReachability.m到项目中,地址:https://github.com/tonymillion/Reachability

  3. 更新接口部分

    #import "Reachability.h"
    
    @interface MyViewController ()
    {
        Reachability *_internetReachableFoo;
    }
    @end
    
  4. .m文件中执行对应的方法

    // 检查我们是否有互联网连接
    - (void)testInternetConnection
    {   
        _internetReachableFoo = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
        // 网络可用
        _internetReachableFoo.reachableBlock = ^(Reachability*reach)
        {
            //主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"网络可用");
            });
        };
    
        // 网络不可用
        _internetReachableFoo.unreachableBlock = ^(Reachability*reach)
        {
            //主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"网络不可用");
            });
        };
    
        [_internetReachableFoo startNotifier];
    }
    

    重要提示:Reachability类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。如果发生这种情况,您将不得不重命名Reachability.hReachability.m为其他名称以便解决问题。

二、主动获取——使用网络时调用方法判断

1.使用Reachability版本

  1. 添加SystemConfigurationframework到项目中

  2. 添加Tony Million’s 版本的Reachability.hReachability.m到项目中,地址:https://github.com/tonymillion/Reachability

  3. 函数

//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>

- (BOOL)connected;

//Class.m
- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}

在需要判断网络连接状态的地方调用方法如下:

if (![self connected]) {
    // Not connected
} else {
    // Connected. Do some Internet stuff
}

2.非Reachability版本

  1. 添加SystemConfigurationframework到项目中
  2. 导入头文件
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
  1. 调用方法
+(BOOL)hasConnectivity {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if (reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // If target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // If target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }


            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs.

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;
}

demo

https://github.com/zhzhl1993/MacOS-Development/tree/master/Demo/TestReachbility

参考文献

How to check for an active Internet connection on iOS or macOS?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jarlen John

谢谢你给我一杯咖啡的温暖

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值