是否有针对WiFi网络更改的NSNotificationCenter通知?

时间:2013-02-24 00:26:12

标签: cocoa events nsnotificationcenter

我想在我的Cocoa应用程序中订阅WiFi网络更改,但我无法找到合适的订阅事件。

是否有针对WiFi网络更改的NSNotificationCenter通知?

3 个答案:

答案 0 :(得分:5)

据我所知。我会使用CoreWLAN获取系统上所有WiFi接口的列表,然后使用SystemConfiguration框架监控其状态。

这是一个命令行示例(错误检查细节,需要ARC):

#import <Foundation/Foundation.h>
#import <CoreWLAN/CoreWLAN.h>
#import <SystemConfiguration/SystemConfiguration.h>

void wifi_network_changed(SCDynamicStoreRef store, CFArrayRef changedKeys, void *ctx)
{
  [(__bridge NSArray *)changedKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
  {
    /* Extract the interface name from the changed key */
    NSString *ifName = [key componentsSeparatedByString:@"/"][3];
    CWInterface *iface = [CWInterface interfaceWithName:ifName];

    NSLog(@"%@ status changed: current ssid is %@, security is %ld",
          ifName, iface.ssid, iface.security);
  }];
}

int main(int argc, char *argv[])
{
  /* Get a list of all wifi interfaces, and build an array of SCDynamicStore keys to monitor */
  NSSet *wifiInterfaces = [CWInterface interfaceNames];
  NSMutableArray *scKeys = [[NSMutableArray alloc] init];
  [wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
  {
    [scKeys addObject:
      [NSString stringWithFormat:@"State:/Network/Interface/%@/AirPort", ifName]];
  }];

  /* Connect to the dynamic store */
  SCDynamicStoreContext ctx = { 0, NULL, NULL, NULL, NULL };
  SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault,
                                                 CFSTR("myapp"),
                                                 wifi_network_changed,
                                                 &ctx);

  /* Start monitoring */
  SCDynamicStoreSetNotificationKeys(store,
                                    (__bridge CFArrayRef)scKeys,
                                    NULL);

  CFRunLoopSourceRef src = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, store, 0);
  CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop],
                     src,
                     kCFRunLoopCommonModes);
  [[NSRunLoop currentRunLoop] run];
}

答案 1 :(得分:3)

只要您打开CWInterface,就可以使用CWLinkDidChangeNotification等通知。在下面的代码中,i_interfaces是一个存储CWInterface数组的ivar,应该在开始时调用monitorWifi,listInterfaces列出接口值,并在任何更改时调用handleInterfaceNotification。

请注意,当接口未连接时,iface.ssid / iface.bssid将为nil。

另请注意,由于各种通知,每次连接/断开连接都会多次调用handleInterfaceNotification。

此代码主要来自NSNotification troubles

-(void) listInterfaces;
{
    NSLog(@"listInterfaces");
    [i_interfaces enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         CWInterface *iface = obj;
         NSLog( @"iface %@, SSID %@, BSSID %@", iface, iface.ssid, iface.bssid );
     }];
}


-(void) handleInterfaceNotification:(NSNotification*) notification;
{
    NSLog(@"Notification Received");
    [self listInterfaces];
}

- (void) monitorWifi;
{
    NSLog(@"monitorWifi");

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWModeDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWSSIDDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWBSSIDDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWCountryCodeDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWLinkDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWPowerDidChangeNotification object:nil];

    NSMutableArray* ifaces = [NSMutableArray new];
    NSSet *wifiInterfaces = [CWInterface interfaceNames];
    [wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
     {
         CWInterface *iface = [CWInterface interfaceWithName:ifName];
         if ( iface ) {
             [ifaces addObject:iface];
         }
     }];
    i_interfaces = ifaces;

    [self listInterfaces];
}

答案 2 :(得分:0)

非常感谢。我需要从Swift执行此操作,所以这里有一些Swift代码可以帮助您入门:

func callback(store: SCDynamicStore, changedKeys: CFArray, 
              context: UnsafeMutableRawPointer?) -> Void {
    // Do the magic
}

// Connect to the store
guard let store = SCDynamicStoreCreate(nil, "myapp" as CFString, callback, nil) else {
    print("Could not connect to store")
    abort()
}

// Setup the notification mechanism for any IPv4 event
var keys = [CFString]()
keys.append("State:/Network/Global/IPv4" as CFString)
SCDynamicStoreSetNotificationKeys(store, keys as CFArray, nil)

// Go into the loop
let runloop = SCDynamicStoreCreateRunLoopSource(nil, store, 0)
let currentLoop = RunLoop.current.getCFRunLoop()
let modes = CFRunLoopMode.commonModes
CFRunLoopAddSource(currentLoop, runloop, modes)
RunLoop.current.run()