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

joh*_*ton 3 events cocoa nsnotificationcenter

我想订阅我的Cocoa应用程序中的WiFi网络更改,但我找不到要订阅的适当事件.

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

jat*_*ben 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];
}
Run Code Online (Sandbox Code Playgroud)