如何在OS X的swift中检测wifi/以太网/热点何时下降



我在SO和苹果文档中搜索过,似乎找不到如何做到这一点。

我有一个正在制作的应用程序,我想检测网络连接何时断开,并在发生这种情况时将"网络断开"打印到控制台。

有可能在OS X上使用swift吗?

1。从github下载。

2.在项目中添加这些文件

Reachability.h
Reachability.m

3.ViewController.h中添加:

@class Reachability; 

4.ViewController.h 中添加变量Reachability* internetReachable;

@interface ViewController : UIViewController {
    Reachability* internetReachable;
}

5.ViewController.m 中添加Reachability.h

#import "ViewController.h"
#import "Reachability.h"

6.在YourViewController.m 中添加以下行

-(void)ViewDidLoad {
    [[NSNotificationCenter defaultCenter] 
                       addObserver:self 
                       selector:@selector(checkNetworkStatus:) 
                       name:kReachabilityChangedNotification 
                       object:nil];
    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];
}

7.添加以下功能

-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            break;
        }
    }
}

希望这能有所帮助!!